diff --git a/README.md b/README.md index d3d19bbb..f58229e6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Base logo

- + [![GitHub contributors](https://img.shields.io/github/contributors/base/docs)](https://github.com/base/docs/graphs/contributors) [![GitHub commit activity](https://img.shields.io/github/commit-activity/w/base/docs)](https://github.com/base/docs/graphs/contributors) @@ -10,7 +10,7 @@ ![GitHub repo size](https://img.shields.io/github/repo-size/base/docs) [![GitHub](https://img.shields.io/github/license/base/docs?color=blue)](https://github.com/base/docs/blob/main/LICENSE.md) - + [![Website base.org](https://img.shields.io/website-up-down-green-red/https/base.org.svg)](https://base.org) [![Blog](https://img.shields.io/badge/blog-up-green)](https://base.mirror.xyz/) @@ -18,149 +18,149 @@ [![Discord](https://img.shields.io/discord/1067165013397213286?label=discord)](https://base.org/discord) [![Twitter Base](https://img.shields.io/twitter/follow/Base?style=social)](https://twitter.com/Base) - + [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr-raw/base/docs)](https://github.com/base/docs/pulls) [![GitHub Issues](https://img.shields.io/github/issues-raw/base/docs.svg)](https://github.com/base/docs/issues) -Base Docs are community-managed. We welcome and encourage contributions from everyone to keep these docs accurate, helpful, and up to date. +Документация Base управляется сообществом. Мы приветствуем и поощряем вклад каждого, чтобы поддерживать эти документы точными, полезными и актуальными. -> Note: This repository powers the public Base documentation site. Content lives under `docs/`. +> Примечание: Этот репозиторий используется для публичного сайта документации Base. Контент находится в папке `docs/`. -## Local development +## Локальная разработка -Prerequisite: Node.js v19+. +Предварительное требование: Node.js v19+. -1. Clone the repository. -2. Install the Mint CLI to preview documentation changes locally: +1. Клонируйте репозиторий. +2. Установите Mint CLI для локального просмотра изменений документации: ```bash npm i -g mint ``` -3. Preview locally (run from the `docs/` directory where `docs.json` lives): +3. Просмотр локально (запустите из директории docs/, где находится docs.json): ```bash cd docs mint dev ``` -Alternatively, without a global install: +Альтернативно, без глобальной установки: ```bash npx mint dev ``` -### Troubleshooting +### Устранение неполадок -- Ensure Node.js v19+ is installed and that you run `mint dev` from the directory containing `docs.json` (usually `docs/`). -- Local preview differs from production: run `mint update` to update the CLI. +- Убедитесь, что установлена Node.js версии 19 или выше, и что вы запускаете команду mint dev из каталога, содержащего файл docs.json (обычно это папка docs/). +- Локальный просмотр отличается от продакшена: выполните `mint update` для обновления CLI. -## How to contribute +## Как внести вклад -1. **Fork and branch**: Fork `base/docs` and create a descriptive branch for your change. -2. **Edit content in `docs/`**: Follow the structure and style guidelines below. Preview locally with the Mint CLI. -3. **Open a pull request**: Provide a clear summary and links to related pages. The docs team and community will review. +1. **Fork and branch (Сделайте форк и ветку)**: Сделайте форк `base/docs` и создайте описательную ветку для ваших изменений. +2. **Edit content in `docs/` (Редактируйте контент в `docs/`)**: Следуйте структуре и стилю, указанным ниже. Просматривайте изменения локально с помощью Mint CLI. +3. **Open a pull request (Откройте pull request)**: Предоставьте четкое описание и ссылки на связанные страницы. Команда документации и сообщество проведут ревью. -> Tip: Prefer small, focused PRs. Link related guides and references directly in your content. +> Совет: Отдавайте предпочтение небольшим, сфокусированным PR (Pull Request). Связывайте связанные руководства и ссылки непосредственно в вашем контенте. -## Documentation structure +## Структура документации -### Core principle: maintain existing structure +### Основной принцип: сохраняйте существующую структуру -> Warning: Do not create new top-level sections. Place all new content within existing folders under `docs/`. +> Предупреждение: Не создавайте новые разделы верхнего уровня. Размещайте весь новый контент в существующих папках внутри `docs/`. -The Base documentation is organized into established sections (for example: `get-started/`, `learn/`, `base-account/`, `base-app/`, `base-chain/`, `cookbook/`, `mini-apps/`, `onchainkit/`). Fit new content into the most relevant existing section. +Документация Base организована в установленные разделы (например: `get-started/`, `learn/`, `base-account/`, `base-app/`, `base-chain/`, `cookbook/`, `mini-apps/`, `onchainkit/`). Размещайте новый контент в наиболее подходящем существующем разделе. -### Navigation policy +### Политика навигации -> Note: We generally do not change the global navigation (top-level tabs) or sidebar sections unless there is a clear, broadly beneficial need. Contributions should focus on improving existing pages and adding new pages within current sections. +> Примечание: Мы обычно не меняем глобальную навигацию (вкладки верхнего уровня) или разделы боковой панели, если нет четкой, широко полезной необходимости. Вклад должен быть сосредоточен на улучшении существующих страниц и добавлении новых страниц в текущих разделах. -### Section purpose and placement +### Назначение и размещение разделов -- **Quickstart**: End-to-end setup to first success. Keep concise and current. -- **Concepts**: Explanations of components, architecture, and design philosophy. -- **Guides**: Step-by-step, action-oriented tutorials for specific tasks. -- **Examples**: Complete, runnable examples demonstrating real-world usage. -- **Technical Reference**: API/method/component specs with parameters and return types. -- **Contribute**: Information for contributors and process updates. +- **Quickstart (Быстрый старт)**: Полная настройка до первого успеха. Сохраняйте лаконичность и актуальность. +- **Concepts (Концепции)**: Объяснения компонентов, архитектуры и философии дизайна. +- **Guides (Руководства)**: Пошаговые, ориентированные на действие туториалы для конкретных задач. +- **Examples (Примеры)**: Полные, запускаемые примеры, демонстрирующие реальное использование. +- **Technical Reference (Техническая справка)**: Спецификации API/методов/компонентов с параметрами и типами возвращаемых значений. +- **Contribute (Вклад)**: Информация для контрибьюторов и обновления процессов. -#### Cookbook scope +#### Область применения Cookbook -- The `cookbook/` section hosts use case-focused guides and patterns, not product-specific documentation. -- Prefer cross-cutting solutions that illustrate how to build on Base across tools and scenarios. +- Раздел `cookbook/` содержит руководства и паттерны, ориентированные на варианты использования, а не на документацию по конкретным продуктам. +- Отдавайте предпочтение комплексным решениям, демонстрирующим, как создавать проекты на Base с использованием различных инструментов и сценариев. -> Warning: Avoid subsection proliferation: -> - Put all guides at the same level within the Guides section. -> - Organize Reference by component/feature, not per use case. -> - Use cross-links instead of adding new structural layers. +> Предупреждение: Избегайте разрастания подразделов: +> - Размещайте все руководства на одном уровне внутри раздела Guides. +> - Организуйте Reference по компонентам/функциям, а не по вариантам использования. +> - Используйте перекрестные ссылки вместо добавления новых структурных слоев. -## Style and formatting +## Стиль и форматирование -### Writing style +### Стиль написания -1. Be concise and consistent; use active voice and second person. -2. Focus on the happy path; mention alternatives briefly where relevant. -3. Use explicit, descriptive headings and filenames. -4. Maintain consistent terminology; introduce abbreviations on first use. +1. Будьте краткими и последовательными; используйте активный залог и второе лицо. +2. Сосредоточьтесь на основном сценарии; кратко упоминайте альтернативы там, где это уместно. +3. Используйте явные, описательные заголовки и имена файлов. +4. Сохраняйте единообразную терминологию; вводите сокращения при первом использовании. -### AI-friendly content +### Контент, удобный для ИИ -- Use clear, explicit language and link related pages directly. -- Prefer bulleted lists for options/steps when not sequential. -- Name and reference libraries and tools explicitly. -- Use semantic, readable URLs and avoid ambiguous abbreviations. +- Используйте ясный, однозначный язык и напрямую связывайте связанные страницы. +- Предпочитайте маркированные списки для опций/шагов, когда они не являются последовательными. +- Явно называйте и ссылайтесь на библиотеки и инструменты. +- Используйте семантические, читаемые URL и избегайте неоднозначных сокращений. -> Checklist: -> - Would a Large Language Model understand and follow this content? -> - Can an engineer copy, paste, and run the examples as-is? +> Контрольный список: +> - Поймёт ли большая языковая модель этот контент и сможет ли корректно следовать ему? +> - Может ли инженер скопировать, вставить и запустить примеры как есть? -### Mintlify formatting +### Форматирование Mintlify -- Start main sections with H2 (`##`) and subsections with H3 (`###`). -- Use fenced code blocks with language and optional filename. -- Wrap images in `` and include `alt` text. -- Use callouts for emphasis: ``, ``, ``, ``, ``. -- For procedures, prefer `` / ``. -- For alternatives, use `` / ``. -- For API docs, use ``, ``, and request/response examples. +- Начинайте основные разделы с H2 (`##`) и подразделы с H3 (`###`). +- Используйте блоки кода с указанием языка и необязательным именем файла. +- Оберните изображения в и добавьте `alt` текст. +- Используйте callouts для выделения: ``, ``, ``, ``, ``. +- Для процедур предпочитайте `` / ``. +- Для альтернатив используйте `` / ``. +- Для документации API используйте ``, `` и примеры запросов/ответов. -### Code examples +### Примеры кода -- Provide complete, runnable examples with realistic data. -- Include proper error handling and edge cases. -- Specify language and filename when helpful. -- Show expected output or verification steps. +- Предоставляйте полные, запускаемые примеры с реалистичными данными. +- Включайте правильную обработку ошибок и граничные случаи. +- Указывайте язык и имя файла, когда это полезно. +- Показывайте ожидаемый вывод или шаги проверки. -## Third-party guides policy +## Политика сторонних руководств -> Warning: We generally do not accept guides that primarily document a third-party product. Exceptions require a clear Base-focused use case and a tight integration with Base products. Simply deploying on Base or connecting to Base Account/Base App is not sufficient. +> Предупреждение: Мы обычно не принимаем руководства, которые в основном документируют сторонний продукт. Исключения требуют четкого варианта использования, ориентированного на Base, и тесной интеграции с продуктами Base. Простое развертывание на Base или подключение к Base Account/Base App недостаточно. -If your goal is to increase discoverability of your product, please request inclusion on the Base Ecosystem page instead. See the instructions for [updating the Base Ecosystem page](https://github.com/base/web?tab=readme-ov-file#updating-the-base-ecosystem-page). +Если ваша цель - повысить видимость вашего продукта, пожалуйста, запросите включение на странице Base Ecosystem вместо этого. Смотрите инструкции по [обновлению страницы Base Ecosystem](https://github.com/base/web?tab=readme-ov-file#updating-the-base-ecosystem-page). -## Review checklist (before submitting a PR) +## Контрольный список для проверки (перед отправкой PR) -- [ ] Fits within existing structure (no new top-level sections) -- [ ] Minimal, necessary subsections only -- [ ] Consistent terminology; abbreviations introduced on first use -- [ ] Code examples are complete, runnable, and validated -- [ ] Cross-links to related guides/examples/references are included -- [ ] Uses Mintlify components and heading hierarchy correctly -- [ ] Accessible images with descriptive `alt` text and frames -- [ ] AI-friendly: explicit, link-rich, and easy to follow +- [ ] Соответствует существующей структуре (без новых разделов верхнего уровня) +- [ ] Только минимальные, необходимые подразделы +- [ ] Единообразная терминология; сокращения вводятся при первом использовании +- [ ] Примеры кода должны быть полными, корректно выполняться и проходить проверку. +- [ ] Включены перекрестные ссылки на связанные руководства/примеры/справочники +- [ ] Корректно использует компоненты Mintlify и иерархию заголовков +- [ ] Доступные изображения с описательным `alt` текстом и фреймами +- [ ] Удобно для ИИ: явный, богатый ссылками и легкий для понимания -## Submission process +## Процесс отправки -1. Create a PR to `https://github.com/base/docs` with your changes. -2. Include a clear description of the change and impacted pages. -3. Request review from the docs team. -4. Address feedback and iterate. -5. Once approved, changes will be merged and published. +1. Создайте PR (pull request) в `https://github.com/base/docs` с вашими изменениями. +2. Включите четкое описание изменений и затронутых страниц. +3. Запросите ревью у команды документации. +4. Учитывайте обратную связь и итерируйте. +5. После одобрения изменения будут объединены и опубликованы. -## Publishing changes +## Публикация изменений -The core team will review opened PRs. The SLA is 2 weeks, generally on a first-come, first-served basis outside of urgent changes. +Основная команда просматривает открытые PR. Время обработки (SLA) составляет 2 недели — обычно в порядке очереди, за исключением срочных изменений. -## Storybook for UI components +## Storybook для UI компонентов -See `storybook/README.md` for details on local Storybook and component docs. +Смотрите `storybook/README.md` для деталей о локальном Storybook и документации компонентов. diff --git a/content-instructions.md b/content-instructions.md index bb1a1a78..f9a04535 100644 --- a/content-instructions.md +++ b/content-instructions.md @@ -1,42 +1,42 @@ -# Mintlify technical writing rule +# Правила технического письма Mintlify. -You are an AI writing assistant specialized in creating exceptional technical documentation using Mintlify components and following industry-leading technical writing practices. +Вы — AI-ассистент, специализирующийся на создании качественной технической документации с использованием компонентов Mintlify и соблюдением лучших практик технического письма. -## Core writing principles +## Основные принципы письма -### Language and style requirements +### Требования к языку и стилю -- Use clear, direct language appropriate for technical audiences -- Write in second person ("you") for instructions and procedures -- Use active voice over passive voice -- Employ present tense for current states, future tense for outcomes -- Avoid jargon unless necessary and define terms when first used -- Maintain consistent terminology throughout all documentation -- Keep sentences concise while providing necessary context -- Use parallel structure in lists, headings, and procedures +- Используйте ясный, прямой язык, подходящий для технической аудитории +- Пишите во втором лице ("вы") для инструкций и процедур +- Используйте активный залог вместо пассивного +- Используйте настоящее время для описания текущих состояний и будущее — для ожидаемых результатов +- Избегайте жаргона, если он не необходим, и определяйте термины при первом использовании +- Сохраняйте единообразную терминологию во всей документации +- Сохраняйте предложения краткими, обеспечивая необходимый контекст +- Используйте параллельную структуру в списках, заголовках и процедурах -### Content organization standards +### Стандарты организации контента -- Lead with the most important information (inverted pyramid structure) -- Use progressive disclosure: basic concepts before advanced ones -- Break complex procedures into numbered steps -- Only include prerequisites and context before instructions when necessary for instructions to be understood -- Provide expected outcomes for each major step -- Use descriptive, keyword-rich headings for navigation and SEO -- Group related information logically with clear section breaks +- Начинайте с самой важной информации (структура перевернутой пирамиды) +- Применяйте прогрессивное раскрытие — сначала базовые концепции, затем продвинутые +- Разбивайте сложные процедуры на нумерованные шаги +- Включайте предварительные требования и контекст перед инструкциями только когда это необходимо для понимания инструкций +- Предоставляйте ожидаемые результаты для каждого основного шага +- Используйте описательные, богатые ключевыми словами заголовки для навигации и SEO +- Группируйте связанную информацию логично с четкими разрывами разделов -### User-centered approach +### Пользовательский подход -- Focus on user goals and outcomes rather than system features -- Anticipate common questions and address them proactively -- Include troubleshooting for likely failure points -- Write for scannability with clear headings, lists, and white space -- Include verification steps to confirm success +- Фокусируйтесь на целях пользователей и результатах, а не на функциях системы +- Предвосхищайте распространенные вопросы и решайте их проактивно +- Включайте устранение неполадок для вероятных точек сбоя +- Пишите текст так, чтобы его было удобно просматривать — используйте чёткие заголовки, списки и достаточные отступы +- Включайте шаги проверки для подтверждения успеха -## Required page structure +## Обязательная структура страницы -Every documentation page must begin with YAML frontmatter: +Каждая страница документации должна начинаться с YAML frontmatter: ```yaml --- @@ -45,49 +45,49 @@ description: "Concise description explaining page purpose and value" --- ``` -## Content quality standards - -### Code examples requirements - - Every code block must have a filename or a title - - if filename, add filename after language (e.g. ```typescript page.tsx```) - - if title, add Title followed by the title (e.g. ```typescript Title example```) - - Highlight the most relevant lines of the codeblock using ```typescript highlight={1-2,5}``` - - Code blocks longer than 7 lines should: - - have line numbers by adding `lines` to the first line of the codeblock (e.g. ```typescript lines```) - - be marked as `expandable` by adding to the first line of the codeblock - - use `wrap` to prevent horizontal scrolling of codeblocks -- Always include complete, runnable examples that users can copy and execute -- Show proper error handling and edge case management -- Use realistic data instead of placeholder values -- Include expected outputs and results for verification -- Add explanatory comments for complex logic -- Never include real API keys or secrets in code examples - -### API documentation requirements - -- Document all parameters including optional ones with clear descriptions -- Show both success and error response examples with realistic data -- Include rate limiting information with specific limits -- Provide authentication examples showing proper format -- Explain all HTTP status codes and error handling -- Cover complete request/response cycles - -### Accessibility requirements - -- Include descriptive alt text for all images and diagrams -- Use specific, actionable link text instead of "click here" -- Ensure proper heading hierarchy starting with H2 -- Provide keyboard navigation considerations -- Use sufficient color contrast in examples and visuals -- Structure content for easy scanning with headers and lists - -## Component selection logic - -- Use **Steps** for procedures and sequential instructions -- Use **Tabs** for platform-specific content or alternative approaches -- Use **CodeGroup** when showing the same concept in multiple programming languages or frameworks -- Use **Accordions** for progressive disclosure of information -- Use **RequestExample/ResponseExample** specifically for API endpoint documentation -- Use **ParamField** for API parameters, **ResponseField** for API responses -- Use **Expandable** for nested object properties or hierarchical information +## Стандарты качества контента + +### Требования к примерам кода + - Каждый блок кода должен иметь имя файла или заголовок + - если имя файла, добавьте его после языка (например, ```typescript page.tsx```) + - если заголовок, добавьте Title с последующим заголовком (например, ```typescript Title example```) + - Выделяйте наиболее релевантные строки блока кода с помощью ```typescript highlight={1-2,5}``` + - Блоки кода длиннее 7 строк должны: + - иметь номера строк путем добавления `lines` к первой строке блока кода (например, ```typescript lines```) + - быть помечены как `expandable` путем добавления к первой строке блока кода + - используйте `wrap` для предотвращения горизонтальной прокрутки блоков кода +- Всегда включайте полные, запускаемые примеры, которые пользователи могут скопировать и выполнить +- Показывайте правильную обработку ошибок и управление граничными случаями +- Используйте реалистичные данные вместо значений-заполнителей +- Включайте ожидаемые выводы и результаты для проверки +- Добавляйте пояснительные комментарии для сложной логики +- Никогда не включайте реальные API-ключи или секреты в примеры кода + +### Требования к документации API + +- Документируйте все параметры, включая опциональные, с четкими описаниями +- Показывайте примеры как успешных, так и ошибочных ответов с реалистичными данными +- Включайте информацию об ограничении частоты запросов с конкретными лимитами +- Предоставляйте примеры аутентификации, показывающие правильный формат +- Объясняйте все HTTP статус-коды и обработку ошибок +- Охватывайте полные циклы запросов/ответов + +### Требования доступности + +- Включайте описательный alt-текст для всех изображений и диаграмм +- Используйте осмысленные и действенные тексты ссылок вместо фраз вроде «нажмите здесь» +- Обеспечьте правильную иерархию заголовков, начиная с H2 +- Предусматривайте возможности навигации с клавиатуры +- Используйте достаточную контрастность цветов в примерах и визуальных элементах +- Структурируйте контент для легкого просмотра с помощью заголовков и списков + +## Логика выбора компонентов + +- Используйте **Steps** для процедур и последовательных инструкций +- Используйте **Tabs** для платформо-специфичного контента или альтернативных подходов +- Используйте **CodeGroup** при показе одной концепции на нескольких языках программирования или фреймворках +- Используйте **Accordions** для прогрессивного раскрытия информации +- Используйте **RequestExample/ResponseExample** специально для документации API endpoints +- Используйте **ParamField** для параметров API, **ResponseField** для ответов API +- Используйте **Expandable** для вложенных свойств объектов или иерархической информации diff --git a/docs/base-account/basenames/basename-transfer.mdx b/docs/base-account/basenames/basename-transfer.mdx index cd92011d..21711676 100644 --- a/docs/base-account/basenames/basename-transfer.mdx +++ b/docs/base-account/basenames/basename-transfer.mdx @@ -1,88 +1,88 @@ --- -title: Basename Transfer Guide +title: Руководство по переносу Basename slug: /basename-transfer -description: 'Step-by-step guide for Base App users to transfer their Basenames to new a wallet addresses.' +description: 'Пошаговое руководство для пользователей Base App по переносу их Basenames на новые адреса кошельков.' --- -# Basename Transfer Guide +# Руководство по переносу Basename -## Transferring Your Basename to Your New Wallet +## Перенос вашего Basename на новый кошелёк -If you have an existing Basename you'd like to use, you'll need to transfer it to your new wallet address. We do not allow import or linking of pre-existing Basenames without transfer at this time. +Если у вас есть существующий Basename, который вы хотите использовать, вам нужно перенести его на новый адрес кошелька. В настоящее время мы не разрешаем импорт или привязку существующих Basenames без переноса. -### Before You Start +### Перед началом - **Your new wallet address is ready**: We've automatically copied your new wallet address to your - clipboard. You'll paste this when prompted. + **Адрес вашего нового кошелька готов**: Мы автоматически скопировали адрес вашего нового кошелька + в ваш буфер обмена. Вы вставите его, когда будет предложено. - **Make sure to use the Basenames UI to send Basenames properly, sends on platforms like OpenSea - will only transfer the NFT.** + **Обязательно используйте интерфейс Basenames для правильной отправки Basenames, отправки на + таких платформах, как OpenSea, перенесут только NFT.** -### Step-by-Step Transfer Process +### Пошаговый процесс переноса -1. **Navigate to Basenames** +1. **Перейдите на Basenames** - - Go to [base.org/names](https://base.org/names) - - Sign in with your current wallet (the one that owns the Basename) + - Перейдите на [base.org/names](https://base.org/names) + - Войдите с помощью вашего текущего кошелька (того, которому принадлежит Basename) -2. **Access Your Basenames** +2. **Получите доступ к вашим Basenames** - - Click **"My Basenames"** in the top right corner - - Find the Basename you want to transfer + - Нажмите **"My Basenames"** в правом верхнем углу + - Найдите Basename, который хотите перенести -3. **Start the Transfer** +3. **Начните перенос** - - Click the **three dots** next to your Basename - - Select **"Transfer name"** + - Нажмите на **три точки** рядом с вашим Basename + - Выберите **"Transfer name"** -4. **Enter Your New Address** +4. **Введите ваш новый адрес** - - When prompted for the destination address, **paste your new wallet address** (Ctrl/Cmd + V) - - The address is already on your clipboard + - Когда будет предложено указать адрес назначения, **вставьте адрес вашего нового кошелька** (Ctrl/Cmd + V) + - Адрес уже находится в вашем буфере обмена -5. **Complete the Transfer** - - Sign all **four transactions** in sequence: - - Transfer token ownership - - Transfer management rights - - Change address resolution - - Send the NFT - - Each transaction updates a different aspect of your Basename ownership +5. **Завершите перенос** + - Подпишите все **четыре транзакции** последовательно: + - Перенос права собственности на токен + - Перенос прав управления + - Изменение разрешения адреса + - Отправка NFT + - Каждая транзакция обновляет разные аспекты владения вашим Basename -### After the Transfer +### После переноса -Once the transfer is complete, you'll need to activate your Basename on your new wallet: +После завершения переноса вам нужно активировать ваш Basename на новом кошельке: -1. Switch to your new wallet -2. Go to [base.org/manage-names](https://base.org/manage-names) -3. Sign in with your new wallet -4. Find your transferred Basename and click the three dots -5. Select **"Set as primary"** and sign the transaction +1. Переключитесь на ваш новый кошелёк +2. Перейдите на [base.org/manage-names](https://base.org/manage-names) +3. Войдите с помощью вашего нового кошелька +4. Найдите ваш перенесённый Basename и нажмите на три точки +5. Выберите **Set as primary** и подпишите транзакцию - **For the new owner to use the basename they will need to confirm by setting it as their primary - name.** + **Чтобы новый владелец мог использовать basename, ему нужно подтвердить, установив его в качестве + основного имени.** -### What This Transfer Includes +### Что включает этот перенос -When you complete all four transactions, you're transferring: +Когда вы завершите все четыре транзакции, вы перенесёте: -**Transfer token ownership** - transfers ownership of the Basename token and associated permissions. -**Transfer management** - transfers ability to manage and update profile records. -**Change address resolution** - Basename will resolve to a new address. +**Перенос права собственности на токен** - переносит право собственности на токен Basename и связанные разрешения. +**Перенос управления** - переносит возможность управлять и обновлять записи профиля. +**Изменение разрешения адреса** - Basename будет разрешаться на новый адрес. -Transferring all 3 to the same address will fully transfer ownership of the Basename to that address. +Перенос всех трёх на один и тот же адрес полностью передаст право собственности на Basename этому адресу. -### Need Help? +### Нужна помощь? -If you encounter any issues during the transfer process, make sure: +Если вы столкнулись с какими-либо проблемами в процессе переноса, убедитесь, что: -- You're using the correct wallet (your old one) to initiate the transfer -- You've pasted the correct new wallet address -- You're completing all four transactions in the sequence +- Вы используете правильный кошелёк (ваш старый) для инициации переноса +- Вы вставили правильный адрес нового кошелька +- Вы завершаете все четыре транзакции в последовательности -Your Basename will be fully functional on your new wallet once the transfer and primary name setup are complete. +Ваш Basename будет полностью функциональным на вашем новом кошельке после завершения переноса и настройки основного имени. diff --git a/docs/base-account/basenames/basenames-faq.mdx b/docs/base-account/basenames/basenames-faq.mdx index 81031fcf..77eecc64 100644 --- a/docs/base-account/basenames/basenames-faq.mdx +++ b/docs/base-account/basenames/basenames-faq.mdx @@ -1,123 +1,123 @@ --- -title: Basenames FAQ +title: Basenames Часто задаваемые вопросы slug: /tools/basenames-faq -description: 'Frequently asked questions on basenames.' +description: 'Часто задаваемые вопросы о Basenames.' --- -## FAQ +## Часто задаваемые вопросы -### 1. What are Basenames? +### 1. Что такое Basenames? -[Basenames](https://base.org/names) are a core onchain building block that enable builders to establish their identity on Base by registering human-readable names for their wallet address(es). They are fully onchain, built on the same technology powering ENS names and deployed on Base. These human-readable names can be used when connecting to onchain apps, and sending and receiving on Base and any other EVM chain. Get your Basename at [base.org/names](https://base.org/names). +[Basenames](https://base.org/names) - это основной ончейн-строительный блок, который позволяет разработчикам устанавливать свою идентичность в Base, регистрируя читаемые человеком имена для своих адресов кошельков. Они полностью ончейновые, построены на той же технологии, что и ENS, и развёрнуты на Base. Эти читаемые имена можно использовать при подключении к ончейн-приложениям, а также для отправки и получения средств на Base и любых других EVM-цепочках. Получите свой Basename на [base.org/names](https://base.org/names). -### 2. What are the Basename registration fees? +### 2. Каковы сборы за регистрацию Basename? -Basenames are priced based on name length, and are designed to be globally accessible. Annual registration fees are as follows: +Цены на Basenames основаны на длине имени и разработаны для глобальной доступности. Годовые сборы за регистрацию следующие: -| Letters | Annual fee | +| Буквы | Годовая плата | | ------- | ---------- | | 3 | 0.1 ETH | | 4 | 0.01 ETH | | 5-9 | 0.001 ETH | | 10+ | 0.0001 ETH | -### 3. How do I get a free or discounted Basename? +### 3. Как получить бесплатный или со скидкой Basename? -You can get one free Basename (5+ letters) for one year if you meet any of the below criteria: +Вы можете получить один бесплатный Basename (5+ букв) на один год, если соответствуете любому из следующих критериев: - [Coinbase Verification](http://coinbase.com/onchain-verify) - [Summer Pass Level 3 NFT](https://wallet.coinbase.com/ocs) - [Buildathon participant NFT](https://onchain-summer.devfolio.co/) - [base.eth NFT holder](https://opensea.io/collection/base-org-base-eth) -- cb.id username (acquired prior to Fri Aug 9, 2024) -- [BNS name owner](http://basename.app) - free 4+ letter name (basename.app) +- cb.id username (полученное до пятницы, 9 августа 2024) +- [BNS name owner](http://basename.app) - бесплатное имя из 4+ букв (basename.app) -An equivalent-value discount of 0.001 ETH will be applied if registering a shorter name, or registering for more than 1 year, with the exception of the BNS name owner discount (valued at 0.01 ETH per unique address). You will need to pay the standard registration fees if you wish to keep your Basename after your initial discount has been fully applied. Discounts are only applied once, and are limited to one per address. Even if you meet multiple criteria, you will only be eligible for a single discount on one Basename. If you satisfy multiple criteria, we will automatically apply the highest-value discount to your registration. +Скидка эквивалентной стоимости в 0.001 ETH будет применена при регистрации более короткого имени или регистрации более чем на 1 год, за исключением скидки для владельца имени BNS (стоимостью 0.01 ETH за уникальный адрес). Вам нужно будет оплатить стандартные сборы за регистрацию, если вы захотите сохранить свой Basename после полного применения начальной скидки. Скидки применяются только один раз и ограничены одной на адрес. Даже если вы соответствуете нескольким критериям, вы будете иметь право только на одну скидку на один Basename. Если вы удовлетворяете нескольким критериям, мы автоматически применим скидку с наибольшей стоимостью к вашей регистрации. -We are always looking to add more discounts. If you or your project have ideas for more discounts, please reach out. +Мы всегда ищем возможности добавить больше скидок. Если у вас или вашего проекта есть идеи по дополнительным скидкам, пожалуйста, свяжитесь с нами. -### 4. Why is there an auction at launch, and how does it work? +### 4. Почему при запуске проводится аукцион и как он работает? -Upon initial launch, there will be a temporary premium placed on all Basenames in the form of a Dutch auction, to ensure a fair and quality distribution of names, and to maximize everyone's chance of getting a name they like without being outcompeted by bots. The premium will start at 100 ETH and decay exponentially over the course of 36 hours. Premiums will be added on to the total registration cost of a Basename. Please note: the premium is intentionally designed to be high so that names can't be instantly bought by bots or traders, and can instead enable fairer access and price discovery for the general public. +При первоначальном запуске на все Basenames будет временно установлена премия в форме голландского аукциона, чтобы обеспечить справедливое и качественное распределение имён и максимизировать шансы каждого получить понравившееся имя без конкуренции с ботами. Премия начнётся со 100 ETH и будет экспоненциально снижаться в течение 36 часов. Премии будут добавляться к общей стоимости регистрации Basename. Обратите внимание: премия специально установлена высокой, чтобы имена не могли быть мгновенно куплены ботами или трейдерами, что позволит обеспечить более справедливый доступ и определение цены для широкой публики. -### 5. Do I have to pay gas to register a Basename? +### 5. Нужно ли платить за газ при регистрации Basename? -If registering with a Base Account, registrations will be gasless, sponsored by Base. +При регистрации с помощью Base Account регистрации будут бесплатными по газу, спонсируемыми Base. -### 6. How long can I register a Basename for? +### 6. На какой срок можно зарегистрировать Basename? -There is no limit to registration length, but there is a minimum of 1 year. +Нет ограничений на продолжительность регистрации, но минимальный срок составляет 1 год. -### 7. How can I use my Basename? +### 7. Как я могу использовать свой Basename? -You can use your Basename across apps in the Base ecosystem, starting with base.org, Onchain Registry, and Onchain Summer Pass. You can also use it for sending and receiving on Base and other EVM chains. +Вы можете использовать свой Basename в приложениях экосистемы Base, начиная с base.org, Onchain Registry и Onchain Summer Pass. Вы также можете использовать его для отправки и получения средств на Base и других EVM-цепочках. -### 8. Is my profile information published onchain? +### 8. Публикуется ли информация моего профиля в ончейне? -Basenames are fully onchain, and therefore any information you publish is recorded onchain, requires a transaction, and will be broadly composable with the rest of the ecosystem. Please do not publish any information you do not wish to be onchain. +Basenames полностью ончейновые, поэтому любая информация, которую вы публикуете, записывается в ончейн, требует транзакции и будет широко композируемой с остальной экосистемой. Пожалуйста, не публикуйте никакую информацию, которую вы не хотите размещать в ончейне. -### 9. How do I set my Basename as my primary name for my address? +### 9. Как установить Basename в качестве основного имени для моего адреса? -You can set your Basename as your primary name through Profile Management. Setting your Basename as your primary name will display it on any wallet or app that has added support for Basenames. +Вы можете установить свой Basename в качестве основного имени через Управление профилем. Установка Basename в качестве основного имени будет отображать его в любом кошельке или приложении, которые добавили поддержку Basenames. -**To set a basename as your primary name:** +**Чтобы установить basename в качестве основного имени:** -- Navigate to [My Basenames](https://www.base.org/manage-names) -- Sign in with the wallet that now owns the basename -- Click the three dots of the basename you want to set as a primary name -- Click "Set as primary" and sign the transaction +- Перейдите в [My Basenames](https://www.base.org/manage-names) +- Войдите с помощью кошелька, которому теперь принадлежит basename +- Нажмите на три точки у basename, который хотите установить в качестве основного имени +- Нажмите "Set as primary" и подпишите транзакцию -### 10. How do I transfer my Basename to another address? +### 10. Как перенести Basename на другой адрес? -You can transfer your Basename to another address through Profile Management: +Вы можете перенести свой Basename на другой адрес через Управление профилем: -**Make sure to use the Basenames UI to send Basenames properly, sends on platforms like OpenSea will only transfer the NFT.** +**Обязательно используйте интерфейс Basenames для правильной отправки Basenames, отправки на таких платформах, как OpenSea, перенесут только NFT.** -Transfer token ownership - transfers ownership of the Basename token and associated permissions. -Transfer management - transfers ability to manage and update profile records. -Change address resolution - Basename will resolve to a new address. -Transferring all 3 to the same address will fully transfer ownership of the Basename to that address. +Перенос права собственности на токен - переносит право собственности на токен Basename и связанные разрешения. +Перенос управления - переносит возможность управлять и обновлять записи профиля. +Изменение разрешения адреса - Basename будет разрешаться на новый адрес. +Перенос всех трёх на один и тот же адрес полностью передаст право собственности на Basename этому адресу. -Step by step: +Пошагово: -- Navigate to [base.org/names](http://base.org/names) -- Sign in with wallet that owns the basename -- Click "My Basenames" in the top right corner -- Click the three dots of the basename you want to transfer and click transfer name -- Paste the ENS or address of the wallet you want to transfer the basename to -- Proceed to sign all four transactions to properly update the basename address, ownership, and profile records. The last transaction will be sending the NFT. +- Перейдите на [base.org/names](http://base.org/names) +- Войдите с помощью кошелька, которому принадлежит basename +- Нажмите "My Basenames" в правом верхнем углу +- Нажмите на три точки у basename, который хотите перенести, и нажмите "transfer name" +- Вставьте ENS или адрес кошелька, на который хотите перенести basename +- Перейдите к подписанию всех четырёх транзакций для правильного обновления адреса basename, права собственности и записей профиля. Последняя транзакция будет отправкой NFT. -**For the new owner to use the basename they will need to confirm by setting it as their [primary name](#9-how-do-i-set-my-basename-as-my-primary-name-for-my-address).** +**Чтобы новый владелец мог использовать basename, ему нужно подтвердить, установив его в качестве [основного имени](#9-как-установить-basename-в-качестве-основного-имени-для-моего-адреса).** -### 11. What happens if I forget to renew my Basename? +### 11. Что произойдёт, если я забуду продлить свой Basename? -If you forget to renew your Name, it will enter a grace period of 90 days, during which you can still renew it. If not renewed during this period, the Basename will become available for others to register. +Если вы забудете продлить своё Имя, оно перейдёт в льготный период продолжительностью 90 дней, в течение которого вы всё ещё можете его продлить. Если не продлить в этот период, Basename станет доступным для регистрации другими. -### 12. What happens if a Basename is not renewed during the grace period? +### 12. Что произойдёт, если Basename не будет продлён в течение льготного периода? -If a Basename is not renewed after the 90 day grace period, it will be subject to a [temporary premium](https://support.ens.domains/en/articles/7900612-temporary-premium) in the form of a Dutch auction. This premium starts at 100ETH and will decay exponentially over the course of 21 days. +Если Basename не будет продлён после 90-дневного льготного периода, на него будет установлена [временная премия](https://support.ens.domains/en/articles/7900612-temporary-premium) в форме голландского аукциона. Эта премия начинается со 100ETH и будет экспоненциально снижаться в течение 21 дня. -### 13. Can I link multiple addresses to my Basename? +### 13. Могу ли я привязать несколько адресов к моему Basename? -Currently, only one address at a time can be linked to a Basename. However, we plan to support multi-address linking in the future. +В настоящее время только один адрес одновременно может быть привязан к Basename. Однако мы планируем поддержать привязку нескольких адресов в будущем. -### 14. I am a builder. How do I integrate Basenames to my app? +### 14. Я разработчик. Как интегрировать Basenames в моё приложение? -If you're a builder looking to integrate Basenames into your app, [OnchainKit](https://onchainkit.xyz/wallet/wallet-dropdown-basename) is the easiest way to get started (tutorial [here](https://docs.base.org/identity/basenames/basenames-onchainkit-tutorial)). If you have ideas for new features or badges that you'd like to integrate with Basenames, we'd love to [hear from you](https://app.deform.cc/form/b9c1c39f-f238-459e-a765-5093ca638075/?page_number=0). +Если вы разработчик и хотите интегрировать Basenames в своё приложение, [OnchainKit](https://onchainkit.xyz/wallet/wallet-dropdown-basename) - это самый простой способ начать (руководство [здесь](https://docs.base.org/identity/basenames/basenames-onchainkit-tutorial)). Если у вас есть идеи по новым функциям или бейджам, которые вы хотели бы интегрировать с Basenames, мы будем рады [услышать вас](https://app.deform.cc/form/b9c1c39f-f238-459e-a765-5093ca638075/?page_number=0). -### 15. How do I get a Basename for my app or project? +### 15. Как получить Basename для моего приложения или проекта? -You can register a Basename for your app just like any other Basename. If a Basename for your app or project is not available, there is a good chance it was reserved. Please reach out to our team or fill out this [form](https://app.deform.cc/form/20372eb6-ec97-4d37-967f-d36f4b7f4eb2) and we will reach out with instructions. +Вы можете зарегистрировать Basename для своего приложения так же, как и любой другой Basename. Если Basename для вашего приложения или проекта недоступен, есть большая вероятность, что он был зарезервирован. Пожалуйста, свяжитесь с нашей командой или заполните эту [форму](https://app.deform.cc/form/20372eb6-ec97-4d37-967f-d36f4b7f4eb2) и мы свяжемся с вами с инструкциями. -### 16. How are Basenames built? +### 16. Как построены Basenames? -Basenames are built using the Ethereum Name Service (ENS) protocol, leveraging its decentralized architecture to ensure secure and efficient name resolution. +Basenames построены с использованием протокола Ethereum Name Service (ENS), используя его децентрализованную архитектуру для обеспечения безопасного и эффективного разрешения имён. -### 17. Do Basenames work on different chains? +### 17. Работают ли Basenames в разных цепочках? -Yes, your Name will work on any chain as long as the app is ENSIP-10 compliant. Note that when sending money or interacting across different chains, you should ensure the receiving platform supports ENS. +Да, ваше Имя будет работать в любой цепочке, если приложение соответствует ENSIP-10. Обратите внимание, что при отправке денег или взаимодействии между разными цепочками вы должны убедиться, что принимающая платформа поддерживает ENS. diff --git a/docs/base-account/basenames/basenames-onchainkit-tutorial.mdx b/docs/base-account/basenames/basenames-onchainkit-tutorial.mdx index e9ecfbd9..5e9d00e7 100644 --- a/docs/base-account/basenames/basenames-onchainkit-tutorial.mdx +++ b/docs/base-account/basenames/basenames-onchainkit-tutorial.mdx @@ -1,58 +1,58 @@ --- title: Basenames + OnchainKit Tutorial slug: /basenames/basenames-onchainkit-tutorial -description: 'A tutorial that teaches how to integrate Basenames to your wagmi/viem App using OnchainKit' +description: 'Руководство по интеграции Basenames в ваше wagmi/viem приложение с использованием OnchainKit' author: hughescoin --- -# Add Basenames to your wagmi/viem App using OnchainKit +# Добавление Basenames в ваше wagmi/viem приложение с помощью OnchainKit -Basenames is now live! But what exactly is it? Basenames allows users to register human-readable names for their addresses and serves as a foundational building block for onchain identity. Think of it as your favorite social media handle, but even bigger. Your Basename is multichain by default and yours forever—no platform can take it away from you (just make sure to pay your fee). +Basenames уже доступны! Но что это такое? Basenames позволяет пользователям регистрировать читаемые человеком имена для своих адресов и служит фундаментальным строительным блоком для ончейн-идентичности. Представьте это как ваш любимый псевдоним в соцсетях, но ещё лучше. Ваш Basename по умолчанию работает в нескольких сетях и принадлежит вам навсегда — никакая платформа не может забрать его у вас (просто не забывайте оплачивать сборы). -Integrating Basenames into your onchain app enhances the user experience by masking complex wallet addresses. Just as domains simplify IP addresses, Basenames do the same for wallet addresses. +Интеграция Basenames в ваше ончейн-приложение улучшает пользовательский опыт, скрывая сложные адреса кошельков. Подобно тому, как домены упрощают IP-адреса, Basenames делают то же самое для адресов кошельков. -OnchainKit is a React component library designed to make building Onchain applications easier. In this tutorial, we'll use the `` component to resolve Basenames. +OnchainKit - это библиотека React-компонентов, разработанная для упрощения создания ончейн-приложений. В этом руководстве мы будем использовать компонент `` для разрешения Basenames. -This demo uses Coinbase Base Account and Coinbase Wallet, but Basenames is supported across many [other wallets]. +В этой демонстрации используется Coinbase Base Account и Coinbase Wallet, но Basenames поддерживаются многими [другими кошельками]. -## Objectives +## Цели -By the end of this tutorial, you should be able to: +К концу этого руководства вы сможете: -- Understand how onchain identity works on the Base network -- Enable users to use their onchain identity in your app using [OnchainKit] +- Понять, как работает ончейн-идентичность в сети Base +- Включить использование ончейн-идентичности пользователями в вашем приложении с помощью [OnchainKit] --- -If you're starting from scratch, you'll need to create a new wagmi project. If you already have an existing wagmi project, you can skip ahead to the section on installing OnchainKit. +Если вы начинаете с нуля, вам нужно создать новый wagmi-проект. Если у вас уже есть существующий wagmi-проект, вы можете перейти к разделу об установке OnchainKit. -To create a new wagmi project using TypeScript and install the required dependencies, run the following command: +Чтобы создать новый wagmi-проект с использованием TypeScript и установить необходимые зависимости, выполните следующую команду: ```bash bun create wagmi ``` -Next, you'll need to install OnchainKit. Run the following command: +Далее вам нужно установить OnchainKit. Выполните следующую команду: ```bash bun add @coinbase/onchainkit ``` -After adding OnchainKit, install all dependencies and start your development server with: +После добавления OnchainKit установите все зависимости и запустите сервер разработки с помощью: ``` bun install && bun run dev ``` -This command will install the necessary dependencies and start a development server. +Эта команда установит необходимые зависимости и запустит сервер разработки. -To follow along with the tutorial effectively, open your web browser and your IDE side by side. This setup will allow you to code and see the changes in real time. +Для эффективного прохождения руководства откройте веб-браузер и вашу IDE рядом. Такая настройка позволит вам программировать и видеть изменения в реальном времени. -### Update Wagmi config +### Обновление конфигурации Wagmi -In this section, we will configure your wagmi project to support the Base blockchain by importing the necessary modules. +В этом разделе мы настроим ваш wagmi-проект для поддержки блокчейна Base, импортировав необходимые модули. -Start by importing the `base` and `baseSepolia` chains into your wagmi config. Navigate to `src/wagmi.ts` and update the file as follows: +Начните с импорта цепочек `base` и `baseSepolia` в вашу конфигурацию wagmi. Перейдите в `src/wagmi.ts` и обновите файл следующим образом: ```typescript wagmi.ts import { http, cookieStorage, createConfig, createStorage } from 'wagmi'; @@ -87,5 +87,5 @@ declare module 'wagmi' { } ``` -This configuration sets up the wagmi project to connect to the Base and BaseSepolia networks, utilizing Coinbase Wallet and other connectors. +Эта конфигурация настраивает wagmi-проект для подключения к сетям Base и BaseSepolia, используя Coinbase Wallet и другие коннекторы. diff --git a/docs/base-account/basenames/basenames-wagmi-tutorial.mdx b/docs/base-account/basenames/basenames-wagmi-tutorial.mdx index ca0667d3..639b503d 100644 --- a/docs/base-account/basenames/basenames-wagmi-tutorial.mdx +++ b/docs/base-account/basenames/basenames-wagmi-tutorial.mdx @@ -1,31 +1,31 @@ --- title: Basenames + Wagmi Tutorial slug: /basenames-tutorial-using-wagmi -description: 'A tutorial that teaches how to integrate Basenames to your wagmi/viem App' +description: 'Руководство по интеграции Basenames в ваше wagmi/viem приложение' author: hughescoin --- -# Add Basenames to your onchain app +# Добавление Basenames в ваше ончейн-приложение -[Basenames] is now live! But what exactly is it? Basenames allows users to register human-readable names for their addresses and serves as a foundational building block for onchain identity. Think of it as your favorite social media handle, but even bigger. Your Basename is multichain by default and yours forever—no platform can take it away from you (just make sure to pay your fee). +[Basenames] теперь доступны! Но что это такое? Basenames позволяет пользователям регистрировать читаемые человеком имена для своих адресов и служит фундаментальным строительным блоком для ончейн-идентичности. Представьте это как ваш любимый псевдоним в соцсетях, но ещё лучше. Ваш Basename по умолчанию работает в нескольких сетях и принадлежит вам навсегда - никакая платформа не может забрать его у вас (просто не забывайте оплачивать сборы). -Integrating Basenames into your onchain app enhances the user experience by masking complex wallet addresses. Just as domains simplify IP addresses, Basenames do the same for wallet addresses. +Интеграция Basenames в ваше ончейн-приложение улучшает пользовательский опыт, скрывая сложные адреса кошельков. Подобно тому, как домены упрощают IP-адреса, Basenames делают то же самое для адресов кошельков. -This tutorial shows you how to display Basenames on behalf of your users. We'll walk through setting up the necessary files and configurations to interact with the Basenames ENS resolver directly. Let's begin! +В этом руководстве показано, как отображать Basenames от имени ваших пользователей. Мы пройдём через настройку необходимых файлов и конфигураций для прямого взаимодействия с резолвером ENS Basenames. Давайте начнём! -## Objectives +## Цели -By the end of this tutorial, you should be able to: +К концу этого руководства вы сможете: -- Understand how onchain identity works on the Base network -- Enable users to use their onchain identity in your app -- Pull metadata from your users' Basename profile +- Понять, как работает ончейн-идентичность в сети Base +- Включить использование ончейн-идентичности пользователями в вашем приложении +- Получать метаданные из профиля Basename ваших пользователей -## Steps +## Шаги -First, create a directory to store the ABI (Application Binary Interface) for the Basenames ENS resolver. The ABI will allow your project to interact with the smart contract that handles Basenames. +Сначала создайте директорию для хранения ABI (Application Binary Interface) для резолвера ENS Basenames. ABI позволит вашему проекту взаимодействовать со смарт-контрактом, который обрабатывает Basenames. -In your project folder, run the following commands: +В папке вашего проекта выполните следующие команды: ```bash mkdir abis @@ -33,23 +33,23 @@ cd abis touch L2ResolverAbi.ts ``` -This will create a new directory named `abis` and a file named L2ResolverAbi.ts within it. +Это создаст новую директорию с именем `abis` и файл L2ResolverAbi.ts внутри неё. -Next, add the following placeholder code to the `L2ResolverAbi.ts` file: +Далее добавьте следующий заглушечный код в файл `L2ResolverAbi.ts`: ```typescriptsrc/abis/L2ResolverAbi.ts export default [ - // ABI information goes here + // Здесь будет информация ABI ] as const; ``` -You will need to replace the placeholder comment with the actual ABI. Here is the link to the full [L2ResolverAbi]. +Вам нужно будет заменить комментарий-заглушку на фактический ABI. Вот ссылка на полный [L2ResolverAbi]. -To interact with the Base blockchain, you will need to update the wagmi configuration. This will allow your project to connect to the Base network and use its features. +Для взаимодействия с блокчейном Base вам нужно обновить конфигурацию wagmi. Это позволит вашему проекту подключаться к сети Base и использовать её возможности. -Update your wagmi.ts file as follows: +Обновите ваш файл wagmi.ts следующим образом: ```typescript wagmi.ts 'use client'; @@ -78,16 +78,16 @@ export default function EthereumProviders({ children }: { children: ReactNode }) } ``` -This code sets up your application to use the Base network, enabling the project to interact with the blockchain. +Этот код настраивает ваше приложение для использования сети Base, позволяя проекту взаимодействовать с блокчейном. -Next, we'll create a new directory to house the functions that will resolve and interact with Basenames. These functions will be responsible for fetching Basename information from the blockchain. +Далее мы создадим новую директорию для размещения функций, которые будут разрешать и взаимодействовать с Basenames. Эти функции будут отвечать за получение информации о Basename из блокчейна. -In your project folder, create the apis directory and add a basenames.tsx file: +В папке вашего проекта создайте директорию apis и добавьте файл basenames.tsx: - -`convertReverseNodeToBytes()`: This function is creating the reverse node so we can look up a name given an address. Each address gets its own reverse record in our registry that's created in a deterministic way. -You can see the implementation of `convertReverseNodeToBytes()` in the [OnchainKit repo] -`BasenameTextRecordKeys`: Metadata (e.g., github, twitter, etc.) are stored as text records so we can look them up based on the enum key. + +`convertReverseNodeToBytes()`: Эта функция создаёт обратный узел, чтобы мы могли найти имя по адресу. Каждый адрес получает свою обратную запись в нашем реестре, созданную детерминированным способом. +Вы можете увидеть реализацию `convertReverseNodeToBytes()` в [репозитории OnchainKit] +`BasenameTextRecordKeys`: Метаданные (например, Github, Twitter и т.д.) хранятся как текстовые записи, чтобы мы могли искать их на основе ключа enum. ```typescript src/apis/basenames.tsx @@ -103,7 +103,7 @@ import { import { base, mainnet } from 'viem/chains'; import L2ResolverAbi from '@/abis/L2ResolverAbi'; -// Function to resolve a Basename +// Функция для разрешения Basename export async function getBasename(address: Address) { try { const addressReverseNode = convertReverseNodeToBytes(address, base.id); @@ -117,21 +117,21 @@ export async function getBasename(address: Address) { return basename as BaseName; } } catch (error) { - // Handle the error accordingly + // Обработайте ошибку соответствующим образом console.error('Error resolving Basename:', error); } } ``` -This code provides the foundation for resolving Basenames using the Base network. +Этот код предоставляет основу для разрешения Basenames с использованием сети Base. -You can find the complete implementation in the full [basenames.tsx] file. +Вы можете найти полную реализацию в полном файле [basenames.tsx]. -Now that the necessary functions are in place, you can implement the Basenames functionality in your app. For this example, we'll modify the `page.tsx` file to display Basename information on the server and client side. +Теперь, когда необходимые функции на месте, вы можете реализовать функциональность Basenames в вашем приложении. Для этого примера мы изменим файл `page.tsx`, чтобы отображать информацию о Basename на стороне сервера и клиента. -Here's how to set it up: +Вот как это настроить: ```typescript src/app/page.tsx import { @@ -210,11 +210,11 @@ export default async function Home() { } ``` -In this example, the Home component fetches Basename data and displays it in both server-side and client-side rendered sections. This allows your app to provide a seamless user experience, showing Basename details like the avatar, description, and associated Twitter handle. +В этом примере компонент Home получает данные Basename и отображает их как в серверно-рендеренной, так и в клиентско-рендеренной секциях. Это позволяет вашему приложению обеспечить бесшовный пользовательский опыт, показывая детали Basename, такие как аватар, описание и связанный Twitter-аккаунт. -## Conclusion +## Заключение -Congratulations! You've successfully integrated Basenames into your project. By setting up the necessary ABI, configuring your wagmi project, and implementing custom functions to resolve and display Basenames, you've enhanced your app's user experience by making wallet addresses more user-friendly. Your users can now enjoy a personalized, recognizable onchain identity across the Base network. Keep exploring and building to unlock even more possibilities with Basenames! +Поздравляем! Вы успешно интегрировали Basenames в ваш проект. Настроив необходимый ABI, сконфигурировав ваш wagmi-проект и реализовав пользовательские функции для разрешения и отображения Basenames, вы улучшили пользовательский опыт вашего приложения, сделав адреса кошельков более удобными для пользователей. Теперь ваши пользователи могут наслаждаться персонализированной, узнаваемой ончейн-идентичностью в сети Base. Продолжайте исследовать и создавать, чтобы открыть ещё больше возможностей с Basenames! [Basenames]: https://www.base.org/names/ [OnchainKit]: https://onchainkit.xyz/ diff --git a/docs/base-account/contribute/contribute-to-base-account-docs.mdx b/docs/base-account/contribute/contribute-to-base-account-docs.mdx index 11c92bf5..14120555 100644 --- a/docs/base-account/contribute/contribute-to-base-account-docs.mdx +++ b/docs/base-account/contribute/contribute-to-base-account-docs.mdx @@ -1,178 +1,177 @@ --- -title: "Contribute to the Base Account Docs" +title: "Участие в документации Base Account" --- -This guide is intended for all contributors who are adding new features, content, or making updates to the Base Account documentation. -Following these guidelines ensures consistency and maintains -the documentation structure, making it easier for developers to find information. +Это руководство предназначено для всех участников, которые добавляют новые функции, контент или вносят обновления в документацию Base Account. +Следование этим рекомендациям обеспечивает единообразие и сохраняет структуру документации, упрощая разработчикам поиск информации. -**Why Documentation is Important** +**Почему документация важна** -Good documentation significantly accelerates developer adoption. Focus on creating content that helps developers understand and implement Base Account features efficiently, while maintaining the documentation's structural integrity. +Хорошая документация значительно ускоряет внедрение разработчиками. Сосредоточьтесь на создании контента, который помогает разработчикам понимать и эффективно внедрять функции Base Account, сохраняя при этом структурную целостность документации. -## Documentation Structure Guidelines +## Рекомендации по структуре документации -### Core Principle: Maintain Existing Structure +### Основной принцип: Сохранение существующей структуры -The Base Account documentation is organized into the following main sections: +Документация Base Account организована в следующие основные разделы: -1. **Quickstart** -2. **Concepts** -3. **Guides** -4. **Examples** -5. **Technical Reference** -6. **Contribute** +1. **Быстрый старт** +2. **Концепции** +3. **Руководства** +4. **Примеры** +5. **Техническая справка** +6. **Участие** - **Do not create new top-level sections** + **Не создавайте новые разделы верхнего уровня** - All new content must fit within these existing sections. + Весь новый контент должен соответствовать этим существующим разделам. -### Section Purpose and Content Placement +### Назначение разделов и размещение контента -When adding new content, determine the appropriate section based on the following criteria: +При добавлении нового контента определите соответствующий раздел на основе следующих критериев: -#### Quickstart +#### Быстрый старт -- End-to-end guides for getting developers up and running quickly -- Should remain focused and concise -- Update only when there are fundamental changes to the initial setup process +- Полные руководства для быстрого запуска разработчиков +- Должны оставаться сфокусированными и краткими +- Обновляйте только при фундаментальных изменениях в процессе начальной настройки -#### Concepts +#### Концепции -- Explanatory content about Base Account components, architecture, and design philosophy -- Add new concept documentation when introducing fundamentally new capabilities or paradigms -- Subsections include: - - Intro - - Built-in Features - - Optional Features - - Additional conceptual topics as needed +- Объяснительный контент о компонентах Base Account, архитектуре и философии дизайна +- Добавляйте новую концептуальную документацию при введении принципиально новых возможностей или парадигм +- Подразделы включают: + - Введение + - Встроенные функции + - Опциональные функции + - Дополнительные концептуальные темы по мере необходимости -#### Guides +#### Руководства -- Step-by-step tutorials for specific tasks and implementation scenarios -- **All guides should live under the main "Guides" section** -- Avoid creating deep hierarchical subsections unless absolutely necessary -- Try to keep the number of subsections to a minimum, preferably only one page per guide -- Although not required, guides should preferably have an accompanying GitHub repository -- Name guides clearly with action-oriented titles (e.g., "Implementing Multi-Signature Verification" rather than "Multi-Sig Guide") +- Пошаговые руководства для конкретных задач и сценариев реализации +- **Все руководства должны находиться в основном разделе "Руководства"** +- Избегайте создания глубоких иерархических подразделов, если это абсолютно не необходимо +- Старайтесь минимизировать количество подразделов, предпочтительно одна страница на руководство +- Хотя и не обязательно, руководства предпочтительно должны иметь сопровождающий репозиторий GitHub +- Называйте руководства чётко с ориентированными на действие заголовками (например, "Реализация проверки мультиподписи" вместо "Руководство по мультиподписи") -#### Examples +#### Примеры -- Complete, working code examples demonstrating real-world use cases -- Each example should be self-contained and fully functional -- Each example should have an accompanying GitHub repository -- Include comments explaining key implementation details -- Examples should cover all of the built-in and optional features of the Base Account +- Полные, рабочие примеры кода, демонстрирующие реальные случаи использования +- Каждый пример должен быть самодостаточным и полностью функциональным +- Каждый пример должен иметь сопровождающий репозиторий GitHub +- Включайте комментарии, объясняющие ключевые детали реализации +- Примеры должны охватывать все встроенные и опциональные функции Base Account -#### Technical Reference +#### Техническая справка -- Comprehensive technical documentation of APIs, methods, components, and configurations -- Structured reference material rather than tutorial content -- Include parameter descriptions, return values, and usage examples -- All technical specifications for new features go here, not in separate sections +- Всесторонняя техническая документация API, методов, компонентов и конфигураций +- Структурированный справочный материал, а не учебный контент +- Включайте описания параметров, возвращаемые значения и примеры использования +- Все технические спецификации для новых функций размещаются здесь, а не в отдельных разделах -#### Contribute +#### Участие -- Information for contributors to the Base Account project -- Update when contribution processes change +- Информация для участников проекта Base Account +- Обновляйте при изменении процессов участия -**Avoiding Subsection Proliferation** -- **For Guides**: Keep all guides at the same level under the Guides section -- **For Technical Reference**: Organize by component or feature, not by use case -- When tempted to add a new subsection, consider if the content could be reorganized to fit existing sections -- Use cross-referencing between related content rather than creating new organizational structures +**Избегание разрастания подразделов** +- **Для руководств**: Держите все руководства на одном уровне в разделе Руководства +- **Для технической справки**: Организуйте по компонентам или функциям, а не по случаям использования +- Когда возникает желание добавить новый подраздел, подумайте, можно ли реорганизовать контент для соответствия существующим разделам +- Используйте перекрёстные ссылки между связанным контентом вместо создания новых организационных структур -## Documentation Style Guidelines +## Рекомендации по стилю документации -### Writing Style +### Стиль письма -1. **Be concise**: Use simple, direct language. Avoid unnecessary words. -2. **Consistency**: Maintain consistent terminology throughout documentation. -3. **Persona-focused**: Think about the persona of the reader and write accordingly. -4. **Happy Path**: Focus on the happy path, but don't forget to mention the alternative paths. -5. [**AI-friendly**](#ai-friendly-writing-tips): Write in a way that is easy for AI to understand and follow. +1. **Будьте краткими**: Используйте простой, прямой язык. Избегайте ненужных слов. +2. **Единообразие**: Сохраняйте единообразную терминологию во всей документации. +3. **Ориентация на пользователя**: Думайте о персонаже читателя и пишите соответственно. +4. **Оптимальный сценарий**: Сосредоточьтесь на оптимальном сценарии, но не забывайте упоминать альтернативные пути. +5. [**Дружественность к AI**](#ai-friendly-writing-tips): Пишите так, чтобы AI мог легко понимать и следовать. -**Make sure to review any AI generated content** +**Обязательно проверяйте любой контент, сгенерированный AI** -If you use AI to generate content: +Если вы используете ИИ для генерации контента: -- Make sure to review it carefully before submission. -- Make sure that the content follows the guidelines in this document. -- Make sure that the content is easy for AI to understand and follow. +- Тщательно проверяйте его перед отправкой. +- Убедитесь, что контент следует рекомендациям в этом документе. +- Убедитесь, что контент легко понять и следовать AI. -### AI-friendly Writing Tips +### Советы по написанию дружественного к AI контента -- Make sure you use explicit language in your file names, headings, and content. -- Make active linking references to the relevant guides and examples. -- Use bulleted lists for steps or options. -- Explicitly name and reference the libraries you are using. -- Use code blocks to highlight code. -- Use semantic urls that make sense even without context. Avoid abbreviations. +- Используйте явный язык в именах файлов, заголовках и содержании. +- Используйте активные ссылки на соответствующие руководства и примеры. +- Используйте маркированные списки для шагов или опций. +- Явно называйте и ссылайтесь на используемые библиотеки. +- Используйте блоки кода для выделения кода. +- Используйте семантические URL-адреса, которые имеют смысл даже без контекста. Избегайте сокращений. - **Think like a Large Language Model** + **Думайте как большая языковая модель** -When writing documentation, think about how a Large Language Model would understand the content. +При написании документации думайте о том, как большая языковая модель поймёт контент. -You should continuously ask yourself: +Постоянно задавайте себе вопросы: -- "Would a Large Language Model be able to understand this content?" -- "Would a Large Language Model be able to follow this content?" -- "Would a Large Language Model be able to use this content?" +- "Сможет ли большая языковая модель понять этот контент?" +- "Сможет ли большая языковая модель следовать этому контенту?" +- "Сможет ли большая языковая модель использовать этот контент" -If you can't answer yes to all of these questions, you need to rewrite the content. +Если вы не можете ответить "да" на все эти вопросы, вам нужно переписать контент. -### Formatting +### Форматирование -1. **Markdown usage**: +1. **Использование Markdown**: - - Use proper heading hierarchy (# for main titles, ## for section headings, etc.) - - Use code blocks with language specification (```javascript) - - Use tables for parameter references - - Use bulleted lists for steps or options + - Используйте правильную иерархию заголовков (# для основных заголовков, ## для заголовков разделов и т.д.) + - Используйте блоки кода с указанием языка (```javascript) + - Используйте таблицы для справочников параметров + - Используйте маркированные списки для шагов или опций -2. **Code examples**: - - Include complete, working code examples - - Comment code thoroughly - - Follow the project's coding style guide +2. **Примеры кода**: + - Включайте полные, рабочие примеры кода + - Тщательно комментируйте код + - Следуйте руководству по стилю кодирования проекта -### Abbreviations and Terminology +### Сокращения и терминология -1. **First reference**: The first time you use an abbreviation or technical term, spell it out followed by the abbreviation in parentheses. Example: "Account Abstraction (AA)" -2. **Consistency**: Use the same term for the same concept throughout the documentation -3. **Technical Reference**: Keep the guides and examples to a minimal size. Put the comprehensive technical details in the Technical Reference section. +1. **Первое упоминание**: При первом использовании сокращения или технического термина напишите его полностью, а затем сокращение в скобках. Пример: "Абстракция аккаунта (AA)" +2. **Единообразие**: Используйте один и тот же термин для одного и того же понятия во всей документации +3. **Техническая справка**: Сводите руководства и примеры к минимальному размеру. Помещайте всесторонние технические детали в раздел Технической справки. -## Review Checklist Before Submission +## Контрольный список перед отправкой -- [ ] Content fits within existing structure -- [ ] No new top-level sections created -- [ ] Minimal subsection creation -- [ ] Consistent terminology used throughout -- [ ] Abbreviations properly introduced -- [ ] Code examples are complete and functional -- [ ] Cross-references to related documentation added -- [ ] Documentation follows style guidelines -- [ ] Documentation is written in a way that is easy for AI to understand and follow +- [ ] Контент соответствует существующей структуре +- [ ] Не созданы новые разделы верхнего уровня +- [ ] Создано минимальное количество подразделов +- [ ] Используется единообразная терминология +- [ ] Сокращения правильно введены +- [ ] Примеры кода полны и функциональны +- [ ] Добавлены перекрёстные ссылки на связанную документацию +- [ ] Документация следует рекомендациям по стилю +- [ ] Документация написана так, чтобы ИИ мог легко понять и следовать -## Submission Process +## Процесс отправки -1. Create a documentation Pull Request (PR) to the [repository](https://github.com/base/docs) with your changes -2. Ensure your PR includes updates to all relevant sections and respects the instructions in this guide -3. Request review from the documentation team -4. Address feedback and make necessary revisions -5. Once approved, the PR will be merged and published +1. Создайте Pull Request (PR) документации в [репозиторий](https://github.com/base/docs) с вашими изменениями +2. Убедитесь, что ваш PR включает обновления всех соответствующих разделов и соблюдает инструкции этого руководства +3. Запросите проверку у команды документации +4. Учтите обратную связь и внесите необходимые правки +5. После одобрения PR будет объединён и опубликован diff --git a/docs/base-account/contribute/security-and-bug-bounty.mdx b/docs/base-account/contribute/security-and-bug-bounty.mdx index c85a54d3..9a205286 100644 --- a/docs/base-account/contribute/security-and-bug-bounty.mdx +++ b/docs/base-account/contribute/security-and-bug-bounty.mdx @@ -1,18 +1,17 @@ --- -title: "Security and Bug Bounty" +title: "Безопасность и программа вознаграждений за уязвимости" --- -## Security Audits +## Аудит безопасности -Base Account has undergone multiple security audits. You can find the full list of our audits in the main Base Account repository. +Base Account прошёл несколько проверок безопасности. Полный список наших аудитов вы можете найти в основном репозитории Base Account. -[Base Account audits](https://github.com/coinbase/smart-wallet/tree/main/audits) +[Аудиты Base Account](https://github.com/coinbase/smart-wallet/tree/main/audits) -## Bug Bounty Program +## Программа вознаграждений за уязвимости -The Coinbase/Base Bug Bounty program is a crowdsourced initiative that rewards security researchers -for responsibly reporting vulnerabilities in Base's smart contracts and infrastructure. +Программа вознаграждений за уязвимости Coinbase/Base - это краудсорсинговое мероприятие, которое вознаграждает исследователей безопасности за ответственное сообщение об уязвимостях в смарт-контрактах и инфраструктуре Base. -To report a bug, please follow the instructions in -the [HackerOne Bug Bounty Program](https://hackerone.com/coinbase?type=team). +Чтобы сообщить об ошибке, пожалуйста, следуйте инструкциям в +[Программе вознаграждений за уязвимости HackerOne.](https://hackerone.com/coinbase?type=team). diff --git a/docs/base-account/framework-integrations/cdp.mdx b/docs/base-account/framework-integrations/cdp.mdx index 8563000d..3908f7b3 100644 --- a/docs/base-account/framework-integrations/cdp.mdx +++ b/docs/base-account/framework-integrations/cdp.mdx @@ -1,50 +1,50 @@ --- title: "Coinbase Developer Platform" -description: "Build onchain apps supporting both Base Account and CDP Embedded Wallets" +description: "Создавайте ончейн-приложения с поддержкой Base Account и встроенных кошельков CDP" --- -# Integrate Base Account with CDP Embedded Wallets +# Интеграция Base Account с встроенными кошельками CDP -Learn how to build an onchain app that seamlessly supports both **existing Base Account users** and **new users** through CDP Embedded Wallets, providing unified authentication and wallet management. +Узнайте, как создать ончейн-приложение, которое бесшовно поддерживает как **существующих пользователей Base Account**, так и **новых пользователей** через встроенные кошельки CDP, предоставляя единую аутентификацию и управление кошельками. -## Overview +## Обзор -This integration enables your app to serve two distinct user types: -- **Existing Base users**: Connect with their Base Account for a familiar experience -- **New onchain users**: Create CDP Embedded Wallets via email, mobile, or social authentication +Эта интеграция позволяет вашему приложению обслуживать два различных типа пользователей: +- **Существующие пользователи Base**: Подключаются со своим Base Account для привычного опыта +- **Новые ончейн-пользователи**: Создают встроенные кошельки CDP через email, мобильную или социальную аутентификацию -Both user types get the same app functionality while using their preferred wallet type. +Оба типа пользователей получают одинаковую функциональность приложения, используя предпочитаемый тип кошелька. -## What you'll build +## Что вы создадите -- **Unified authentication flow**: Single sign-in supporting both wallet types -- **Automatic wallet detection**: Smart routing based on user's existing wallet status -- **Consistent user experience**: Both wallet types access the same app features +- **Единый процесс аутентификации**: Единый вход, поддерживающий оба типа кошельков +- **Автоматическое определение кошелька**: Умная маршрутизация на основе существующего статуса кошелька пользователя +- **Последовательный пользовательский опыт**: Оба типа кошельков получают доступ к одинаковым функциям приложения -## Prerequisites +## Предварительные требования -- Node.js 18+ installed -- React application (Next.js recommended) -- [CDP Portal account](https://portal.cdp.coinbase.com/) with Project ID -- Basic familiarity with Wagmi and React hooks +- Установленный Node.js 18+ +- React-приложение (рекомендуется Next.js) +- [Аккаунт CDP Portal](https://portal.cdp.coinbase.com/) с Project ID +- Базовое знакомство с Wagmi и React-хуками -## Installation +## Установка -Install the required packages for both CDP Embedded Wallets and Base Account support: +Установите необходимые пакеты для поддержки как встроенных кошельков CDP, так и Base Account: ```bash npm install @coinbase/cdp-core @coinbase/cdp-hooks @base-org/account @tanstack/react-query viem wagmi ``` -## Step-by-step implementation +## Пошаговая реализация -Since native CDP + Base Account integration is under development, this guide uses a **dual connector approach** where both wallet types are supported through separate, coordinated connectors. +Поскольку нативная интеграция CDP + Base Account находится в разработке, это руководство использует подход с двойными коннекторами, где оба типа кошельков поддерживаются через отдельные, но согласованные коннекторы. -You can use the Base Account Wagmi connector alongside CDP's React provider system to create a unified experience that properly handles wallet persistence for both wallet types. +Вы можете использовать коннектор Wagmi для Base Account вместе с системой провайдеров React от CDP, чтобы создать единый опыт, который правильно обрабатывает сохранение кошельков для обоих типов. -### Step 1: Environment configuration +### Шаг 1: Конфигурация окружения -Create environment variables for your CDP project: +Создайте переменные окружения для вашего проекта CDP: ```bash # .env.local @@ -52,13 +52,13 @@ NEXT_PUBLIC_CDP_PROJECT_ID=your_cdp_project_id NEXT_PUBLIC_APP_NAME="Your App Name" ``` -Get your CDP Project ID from the [CDP Portal](https://portal.cdp.coinbase.com/). +Получите ваш Project ID CDP в [CDP Portal](https://portal.cdp.coinbase.com/). -⚠️ **Critical**: Without a valid `NEXT_PUBLIC_CDP_PROJECT_ID`, the app will fail to load with "Project ID is required" errors. Also configure your domain in CDP Portal → Wallets → Embedded Wallet settings for CORS. +⚠️ **Критично**: Без действительного `NEXT_PUBLIC_CDP_PROJECT_ID` приложение не загрузится с ошибкой "Project ID is required". Также настройте ваш домен в CDP Portal → Wallets → Embedded Wallet settings для CORS. -### Step 2: Configure Wagmi for Base Account support +### Шаг 2: Настройка Wagmi для поддержки Base Account -Set up Wagmi with the Base Account connector (embedded wallets will be handled separately via CDP React providers): +Настройте Wagmi с коннектором Base Account (встроенные кошельки будут обрабатываться отдельно через провайдеры React от CDP): ```typescript // config/wagmi.ts @@ -66,15 +66,15 @@ import { createConfig, http } from 'wagmi'; import { base, baseSepolia } from 'wagmi/chains'; import { baseAccount } from 'wagmi/connectors'; -// Base Account connector +// Коннектор Base Account const baseAccountConnector = baseAccount({ appName: process.env.NEXT_PUBLIC_APP_NAME || 'Your App', }); -// Wagmi config (only for Base Account - embedded wallets handled by CDP React providers) +// Конфигурация Wagmi (только для Base Account - встроенные кошельки обрабатываются провайдерами React от CDP) export const wagmiConfig = createConfig({ connectors: [baseAccountConnector], - chains: [baseSepolia, base], // Put baseSepolia first for testing + chains: [baseSepolia, base], // Сначала baseSepolia для тестирования transports: { [base.id]: http(), [baseSepolia.id]: http(), @@ -82,9 +82,9 @@ export const wagmiConfig = createConfig({ }); ``` -### Step 3: Set up application providers +### Шаг 3: Настройка провайдеров приложения -Wrap your application with the necessary providers. **Important**: Use `CDPHooksProvider` to properly manage embedded wallet authentication state: +Оберните ваше приложение необходимыми провайдерами. Важно: Используйте `CDPHooksProvider` для корректного управления состоянием аутентификации встроенных кошельков: ```typescript // app/layout.tsx @@ -122,9 +122,9 @@ export default function RootLayout({ } ``` -### Step 4: Create unified authentication hook +### Шаг 4: Создание универсального хука аутентификации -Build a custom hook to manage both wallet types. Using `CDPHooksProvider` ensures users get their existing embedded wallets when they sign in again, rather than creating new ones each time. +Создайте пользовательский хук для управления обоими типами кошельков. Использование `CDPHooksProvider` гарантирует, что пользователи получат свои существующие встроенные кошельки при повторном входе, а не создают новые каждый раз. ```typescript @@ -136,12 +136,12 @@ import { useState, useEffect } from 'react'; export type WalletType = 'base_account' | 'embedded' | 'none'; export function useUnifiedAuth() { - // Wagmi hooks for Base Account + // Wagmi хуки для Base Account const { address: wagmiAddress, isConnected: wagmiConnected, connector } = useAccount(); const { connect, connectors } = useConnect(); const { disconnect: wagmiDisconnect } = useDisconnect(); - // CDP hooks for embedded wallet - these work with CDPHooksProvider + // CDP хуки для встроенного кошелька - работают с CDPHooksProvider const { signInWithEmail, isLoading: isSigningIn } = useSignInWithEmail(); const { verifyEmailOTP, isLoading: isVerifying } = useVerifyEmailOTP(); const { isSignedIn: cdpSignedIn } = useIsSignedIn(); @@ -151,7 +151,7 @@ export function useUnifiedAuth() { const [walletType, setWalletType] = useState('none'); const [flowId, setFlowId] = useState(''); - // Determine which wallet is active and prioritize the active one + // Определяем, какой кошелек активен, и приоритезируем активный const address = wagmiConnected ? wagmiAddress : cdpAddress; const isConnected = wagmiConnected || cdpSignedIn; @@ -176,7 +176,7 @@ export function useUnifiedAuth() { try { const response = await signInWithEmail({ email }); - // Capture flowId for OTP verification + // Захватываем flowId для верификации OTP if (response && typeof response === 'object' && 'flowId' in response) { setFlowId(response.flowId as string); } @@ -190,7 +190,7 @@ export function useUnifiedAuth() { const verifyOtpAndConnect = async (otp: string) => { try { - // With CDPReactProvider, verifyEmailOTP automatically signs the user in + // С CDPReactProvider verifyEmailOTP автоматически входит пользователя await verifyEmailOTP({ flowId, otp }); return true; } catch (error) { @@ -227,9 +227,9 @@ export function useUnifiedAuth() { } ``` -### Step 5: Build authentication component +### Шаг 5: Создание компонента аутентификации -Create a component that presents both authentication options: +Создайте компонент, который представляет оба варианта аутентификации: ```typescript // components/WalletAuthButton.tsx @@ -255,7 +255,7 @@ export function WalletAuthButton() { const [email, setEmail] = useState(''); const [otp, setOtp] = useState(''); - // Connected state + // Состояние подключения if (isConnected && address) { const walletDisplay = { base_account: { name: 'Base Account', icon: '🟦' }, @@ -278,7 +278,7 @@ export function WalletAuthButton() { ); } - // OTP verification + // Верификация OTP if (authStep === 'otp') { return (
@@ -316,7 +316,7 @@ export function WalletAuthButton() { ); } - // Email input + // Ввод email if (authStep === 'email') { return (
@@ -353,7 +353,7 @@ export function WalletAuthButton() { ); } - // Initial selection + // Начальный выбор return (

Connect Your Wallet

@@ -388,9 +388,9 @@ export function WalletAuthButton() { } ``` -### Step 6: Handle transactions for each wallet type +### Шаг 6: Обработка транзакций для каждого типа кошелька -Create a transaction component that adapts to each wallet type: +Создайте компонент транзакций, адаптированный для каждого типа кошелька: ```typescript // components/SendTransaction.tsx @@ -423,7 +423,7 @@ export function SendTransaction() { } }; - // Show different guidance based on wallet type + // Показываем различные инструкции в зависимости от типа кошелька const getTransactionGuidance = () => { switch (walletType) { case 'base_account': @@ -539,9 +539,9 @@ export function SendTransaction() { } ``` -### Step 7: Complete your app +### Шаг 7: Завершите ваше приложение -Put everything together in your main application: +Объедините все компоненты в вашем основном приложении: ```typescript // app/page.tsx @@ -574,44 +574,44 @@ export default function HomePage() { } ``` -## Troubleshooting +## Устранение неполадок -### Common Issues +### Распространенные проблемы -**Base Account connector not appearing** -- Verify the Base Account SDK, `@base-org/account`, is installed and up-to-date -- Check wagmi configuration includes Base Account connector -- Ensure app is running on Base or Base Sepolia network +**Коннектор Base Account не появляется** +- Убедитесь, что Base Account SDK, `@base-org/account`, установлен и обновлен +- Проверьте, что конфигурация wagmi включает коннектор Base Account +- Убедитесь, что приложение запущено в сети Base или Base Sepolia -**CDP Embedded Wallet authentication failing** -- Verify CDP Project ID is correct in environment variables -- **Critical**: Add your domains (e.g., `http://localhost:3000`, `http://localhost:3001`) to CDP Portal → Wallets → Embedded Wallet settings → Allowed domains -- Ensure all required CDP packages (see above) are installed +**Сбой аутентификации встроенного кошелька CDP** +- Убедитесь, что Project ID CDP указан правильно в переменных окружения +- **Критично**: Добавьте ваши домены (например, `http://localhost:3000`, `http://localhost:3001`) в CDP Portal → Wallets → Embedded Wallet settings → Allowed domains +- Убедитесь, что все необходимые пакеты CDP (см. выше) установлены -**New wallet created each time instead of signing into existing wallet** -- Ensure you're using `CDPHooksProvider` with proper config in your layout -- Verify CDP Project ID is correctly configured -- Check that hooks are imported from `@coinbase/cdp-hooks` consistently +**Создается новый кошелек каждый раз вместо входа в существующий** +- Убедитесь, что вы используете `CDPHooksProvider` с правильной конфигурацией в вашем layout +- Проверьте, что CDP Project ID корректно настроен +- Убедитесь, что хуки импортируются из `@coinbase/cdp-hooks` последовательно -**Users can't switch between wallet types** -- Implement proper disconnect flow before connecting different type -- Clear any cached authentication state when switching -- Provide clear UI guidance for wallet type selection +**Пользователи не могут переключаться между типами кошельков** +- Реализуйте правильный процесс отключения перед подключением другого типа +- Очистите все кэшированные состояния аутентификации при переключении +- Предоставьте четкие UI-инструкции для выбора типа кошелька -## Enhanced integration coming soon +## Улучшенная интеграция скоро появится -We are actively working on native Base Account integration with CDP Embedded Wallets that will enable: +Мы активно работаем над нативной интеграцией Base Account с встроенными кошельками CDP, которая позволит: -- **Unified connector**: Single CDP connector to handle both wallet types seamlessly -- **Spend permissions**: Sub Accounts will be able to access parent Base Account balance with limits -- **Sub Account creation**: Base Account users will be able to create app-specific Sub Accounts +- **Единый коннектор**: Единый коннектор CDP для бесшовной работы с обоими типами кошельков +- **Разрешения на траты**: Субаккаунты смогут получать доступ к балансу родительского Base Account с ограничениями +- **Создание субаккаунтов**: Пользователи Base Account смогут создавать субаккаунты, привязанные к конкретным приложениям -## Resources +## Ресурсы -- [CDP Embedded Wallets Documentation](https://docs.cdp.coinbase.com/embedded-wallets/) -- [CDP React Components Documentation](https://docs.cdp.coinbase.com/embedded-wallets/components) -- [Base Account Wagmi Setup](/base-account/framework-integrations/wagmi/setup) +- [Документация встроенных кошельков CDP](https://docs.cdp.coinbase.com/embedded-wallets/) +- [Документация React-компонентов CDP](https://docs.cdp.coinbase.com/embedded-wallets/components) +- [Настройка Wagmi для Base Account](/base-account/framework-integrations/wagmi/setup) - [CDP Portal](https://portal.cdp.coinbase.com/) -- [Wagmi Documentation](https://wagmi.sh/) +- [Документация Wagmi](https://wagmi.sh/) -Monitor the [CDP documentation](https://docs.cdp.coinbase.com/) for updates on enhanced Embedded Wallet Base Account integration features. \ No newline at end of file +Следите за [документацией CDP](https://docs.cdp.coinbase.com/) для получения обновлений о расширенных функциях интеграции встроенных кошельков с Base Account. diff --git a/docs/base-account/framework-integrations/nextjs-with-dynamic.mdx b/docs/base-account/framework-integrations/nextjs-with-dynamic.mdx index fe275898..e9bd82e4 100644 --- a/docs/base-account/framework-integrations/nextjs-with-dynamic.mdx +++ b/docs/base-account/framework-integrations/nextjs-with-dynamic.mdx @@ -1,13 +1,14 @@ --- title: "Dynamic" -description: "Integrate Base Account with Dynamic" +description: "Интеграция Base Account с Dynamic" --- -We are working with [Dynamic](https://www.dynamic.xyz/) to integrate Base Account with their SDK. +Мы работаем с [Dynamic](https://www.dynamic.xyz/) над интеграцией Base Account с их SDK. A full guide and example will be available soon. -In the meantime, you can use the connector from the [Wagmi guide](/base-account/framework-integrations/wagmi/setup) -with [Dynamic+Wagmi](https://www.dynamic.xyz/docs/react-sdk/using-wagmi) as a workaround. +Полное руководство и пример будут доступны в ближайшее время. +А пока вы можете использовать коннектор из [руководства по Wagmi](/base-account/framework-integrations/wagmi/setup) +вместе с [Dynamic+Wagmi](https://www.dynamic.xyz/docs/react-sdk/using-wagmi) в качестве временного решения. diff --git a/docs/base-account/framework-integrations/privy/authentication.mdx b/docs/base-account/framework-integrations/privy/authentication.mdx index 4fac05f7..75f7014a 100644 --- a/docs/base-account/framework-integrations/privy/authentication.mdx +++ b/docs/base-account/framework-integrations/privy/authentication.mdx @@ -1,43 +1,41 @@ --- -title: "Auth (Sign In With Base)" -description: "Manage user authentication with Privy and Base Account" +title: "Аутентификация (Sign In With Base)" +description: "Управляйте аутентификацией пользователей с помощью Privy и Base Account" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx"; -Learn how to handle authentication flows with Privy and Base Account, including both Privy-managed authentication and custom backend verification. +Узнайте, как обрабатывать потоки аутентификации с Privy и Base Account, включая как аутентификацию, управляемую Privy, так и пользовательскую проверку на бэкенде. -## Overview +## Обзор -Privy handles the initial authentication flow, managing user sessions and wallet connections. You can also implement additional authentication layers for enhanced security or custom requirements. +Privy обрабатывает первоначальный поток аутентификации, управляя сессиями пользователей и подключениями кошельков. Вы также можете реализовать дополнительные уровни аутентификации для повышенной безопасности или пользовательских требований. -The code snippets in this guide are based on the following example project: +Фрагменты кода в этом руководстве основаны на следующем примере проекта: -## Authentication Flow +## Поток аутентификации -Privy manages the primary authentication before users enter your application: +Privy управляет основной аутентификацией до того, как пользователи войдут в ваше приложение:
Privy Base Auth
-## Custom Authentication +## Пользовательская аутентификация -For additional security or custom authentication requirements, you can implement backend verification using Sign-In with Ethereum (SIWE) -with the Base Account SDK. +Для дополнительной безопасности или пользовательских требований к аутентификации вы можете реализовать проверку на бэкенде с использованием Sign-In with Ethereum (SIWE) и SDK Base Account. -### Setup +### Настройка -Follow the [Setup](/base-account/framework-integrations/privy/setup) guide to set up Privy with Base Account. +Следуйте руководству [настройки](/base-account/framework-integrations/privy/setup) чтобы настроить Privy с Base Account. -### Frontend Component (Sign In With Base) +### Фронтенд-компонент (Sign In With Base) -We use the [`SignInWithBaseButton`](/base-account/reference/ui-elements/sign-in-with-base-button) component from the `@base-org/account-ui/react` package to make sure -we are following the brand guidelines. +Мы используем компонент [`SignInWithBaseButton`](/base-account/reference/ui-elements/sign-in-with-base-button) из пакета `@base-org/account-ui/react`, чтобы обеспечить соответствие руководству по бренду. ```tsx Authentication Component (components/sections/authentication.tsx) expandable @@ -60,17 +58,17 @@ export const Authentication = () => { try { setLoading(true); - // Get a fresh nonce from backend + // Получаем свежий nonce с бэкенда const nonceResponse = await fetch("/api/auth/nonce"); const { nonce } = await nonceResponse.json(); - // Switch to Base Chain + // Переключаемся на сеть Base await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: "0x2105" }], }); - // Connect and authenticate with SIWE + // Подключаемся и аутентифицируемся с помощью SIWE const response = (await provider.request({ method: "wallet_connect", params: [{ @@ -94,7 +92,7 @@ export const Authentication = () => { const { address } = response.accounts[0]; const { message, signature } = response.accounts[0].capabilities.signInWithEthereum; - // Verify with backend + // Проверяем на бэкенде const verifyResponse = await fetch("/api/auth/verify", { method: "POST", headers: { "Content-Type": "application/json" }, @@ -124,9 +122,9 @@ export default Authentication; ``` -### Using the Authentication Component +### Использование компонента аутентификации -Add the Authentication component to your page to enable Sign In with Base functionality: +Добавьте компонент Authentication на вашу страницу, чтобы включить функциональность Sign In with Base: ```tsx Page Implementation (app/page.tsx) @@ -181,10 +179,10 @@ export default function Dashboard() { ``` -### Backend Implementation +### Реализация бэкенда -**Development Only**: This backend implementation is not production-ready. The nonce management system needs proper persistence and security enhancements for production use. +**Только для разработки**: Эта реализация бэкенда не готова для продакшена. Система управления nonce требует правильного постоянного хранения и улучшений безопасности для использования в производственной среде. @@ -223,7 +221,7 @@ export async function POST(request: NextRequest) { try { const { address, message, signature } = await request.json(); - // Extract nonce from SIWE message + // Извлекаем nonce из сообщения SIWE const nonce = message.match(/Nonce: (\w+)/)?.[1]; if (!nonce || !nonceStore.consume(nonce)) { @@ -233,7 +231,7 @@ export async function POST(request: NextRequest) { ); } - // Verify signature using viem + // Проверяем подпись с помощью viem const valid = await client.verifyMessage({ address: address as `0x${string}`, message, @@ -263,8 +261,8 @@ export async function POST(request: NextRequest) { ``` ```ts Nonce Store (lib/nonce-store.ts) expandable -// Simple in-memory nonce store -// In production, use Redis or a database +// Простое хранилище nonce в памяти +// В продакшене используйте Redis или базу данных class NonceStore { private nonces = new Set(); @@ -281,11 +279,11 @@ export const nonceStore = new NonceStore(); ``` -### Production Considerations +### Рекомендации для продакшена -For production deployments, enhance the backend implementation with: +Для развертывания в продакшен улучшите реализацию бэкенда следующим образом: -- **Persistent storage**: Use Redis or a database instead of in-memory storage -- **Rate limiting**: Implement request rate limiting for nonce generation -- **Session management**: Create proper JWT tokens or session cookies -- **Nonce expiration**: Add timestamp-based nonce expiration +**Постоянное хранение**: Используйте Redis или базу данных вместо хранения в памяти +**Ограничение запросов (Rate limiting)**: Реализуйте ограничение частоты запросов для генерации nonce +**Управление сессиями**: Создавайте правильные JWT-токены или куки сессий +**Срок действия nonce**: Добавьте истечение срока действия nonce на основе меток времени diff --git a/docs/base-account/framework-integrations/privy/setup.mdx b/docs/base-account/framework-integrations/privy/setup.mdx index c7a81764..4ae1f70d 100644 --- a/docs/base-account/framework-integrations/privy/setup.mdx +++ b/docs/base-account/framework-integrations/privy/setup.mdx @@ -1,37 +1,37 @@ --- -title: "Setup" -description: "Configure Privy with Base Account for your React application" +title: "Настройка" +description: "Настройте Privy с Base Account для вашего React-приложения" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx"; -Learn how to set up Privy with Base Account to enable seamless user authentication and wallet management. +Узнайте, как настроить Privy с Base Account для включения бесшовной аутентификации пользователей и управления кошельками. -## Overview +## Обзор -[Privy](https://www.privy.io/) provides user authentication and wallet management solutions for onchain applications. -By integrating Privy with Base Account, -you can access all the Privy hooks and methods -while having access to the users of Base Account. +[Privy](https://www.privy.io/) предоставляет решения для аутентификации пользователей и управления кошельками в ончейн-приложениях. +Интегрируя Privy с Base Account, вы +получаете доступ ко всем хукам и методам Privy, +а также к пользователям Base Account. -### What you'll achieve +### Что вы получите -By the end of this guide, you will: +К концу этого руководства вы: -- Set up Privy with Base Account support -- Have Base Account set up as the main authentication option -- Be able to access Base Account SDK from Privy's React SDK +- Настроите Privy с поддержкой Base Account +- Установите Base Account как основной вариант аутентификации +- Сможете получить доступ к Base Account SDK из React SDK Privy -You can jump ahead and use the [Base Account Privy Template](https://github.com/base/base-account-privy) to get started. +Вы можете сразу перейти к использованию [шаблону Base Account Privy](https://github.com/base/base-account-privy) чтобы начать работу. -## Installation +## Установка -### 1. Create a new Next.js project +### 1. Создайте новый проект Next.js ```bash npm npx create-next-app@latest base-account-privy @@ -44,71 +44,71 @@ cd base-account-privy ``` -### 2. Override the Base Account SDK version +### 2. Переопределите версию Base Account SDK -In order to access the latest version of the Base Account SDK, you need to override the Privy pinned version in your package.json file. +Чтобы получить доступ к последней версии Base Account SDK, вам нужно переопределить версию, зафиксированную Privy, в вашем файле package.json. -To do this, you can use the following command to override it: +Для этого вы можете использовать следующую команду: ```bash npm npm pkg set overrides.@base-org/account="latest" -# OR manually add to package.json: +# ИЛИ добавьте вручную в package.json: # "overrides": { "@base-org/account": "latest" } ``` ```bash pnpm -# pnpm requires manual addition to package.json: +# pnpm требует ручного добавления в package.json: # "pnpm": { "overrides": { "@base-org/account": "latest" } } ``` ```bash yarn -# yarn uses resolutions - add manually to package.json: +# yarn использует resolutions - добавьте вручную в package.json: # "resolutions": { "@base-org/account": "latest" } ``` ```bash bun -# bun supports overrides - add manually to package.json: +# bun поддерживает overrides - добавьте вручную в package.json: # "overrides": { "@base-org/account": "latest" } ``` -Or you can use a specific version by adding the version to the overrides: +Или вы можете использовать конкретную версию, добавив ее в `overrides`: ```bash npm npm pkg set overrides.@base-org/account="2.2.0" -# OR manually add to package.json: +# ИЛИ добавьте вручную в package.json: # "overrides": { "@base-org/account": "2.2.0" } ``` ```bash pnpm -# pnpm requires manual addition to package.json: +# pnpm требует ручного добавления в package.json: # "pnpm": { "overrides": { "@base-org/account": "2.2.0" } } ``` ```bash yarn -# yarn uses resolutions - add manually to package.json: +# yarn использует resolutions - добавьте вручную в package.json: # "resolutions": { "@base-org/account": "2.2.0" } ``` ```bash bun -# bun supports overrides - add manually to package.json: +# bun поддерживает overrides - добавьте вручную в package.json: # "overrides": { "@base-org/account": "2.2.0" } ``` -**If you're not starting a new projects** +**Если вы не начинаете новый проект** -Make sure to delete your `node_modules` and `package-lock.json` and run a new install to ensure the overrides are applied. +Убедитесь, что удалили папку `node_modules` и файл `package-lock.json`, а затем выполните новую установку, чтобы переопределения применились. -### 3. Install the dependencies +### 3. Установите зависимости -Install the dependencies with your package manager of choice: +Установите зависимости с помощью вашего предпочтительного менеджера пакетов: ```bash npm @@ -129,21 +129,21 @@ bun add @privy-io/react-auth @privy-io/chains @privy-io/wagmi-connector wagmi vi -## Configuration +## Конфигурация -### 1. Set up Environment Variables +### 1. Настройте переменные окружения -Create a `.env.local` file in your project root: +Создайте файл `.env.local` в корне вашего проекта: ```bash NEXT_PUBLIC_PRIVY_APP_ID=your_privy_app_id ``` -Get your Privy App ID from the [Privy Dashboard](https://dashboard.privy.io/). +Получите ваш Privy App ID в [панеле управлений Privy](https://dashboard.privy.io/). -### 2. Configure Privy Provider +### 2. Настройте провайдер Privy -Create your Privy configuration with Base Account as the default login method and update the layout to include the `PrivyProvider`. +Создайте конфигурацию Privy с Base Account в качестве метода входа по умолчанию и обновите layout, чтобы включить `PrivyProvider`. ```tsx Create Provider (app/providers.tsx) expandable @@ -208,11 +208,11 @@ export default function RootLayout({ ``` -## Usage +## Использование -### 1. Update the App Page +### 1. Обновите главную страницу приложения -Update the `app/page.tsx` file to show the authentication flow: +Обновите файл `app/page.tsx`, чтобы показать процесс аутентификации: ```tsx app/page.tsx expandable "use client"; @@ -282,9 +282,9 @@ function Home() { export default Home; ``` -### 2. Run the project locally +### 2. Запустите проект локально -You're done! You can now run the project locally: +Готово! Теперь вы можете запустить проект локально: ```bash npm @@ -301,15 +301,15 @@ bun dev ``` -You should see a page that looks like this: +Вы должны увидеть страницу, которая выглядит следующим образом:
Base × Privy Demo
-### 3. Get the Base Account SDK instance (Optional) +### 3. Получите экземпляр Base Account SDK (Опционально) -You can access the Base Account SDK from Privy using the `useBaseAccount` hook. +Вы можете получить доступ к Base Account SDK из Privy с помощью хука `useBaseAccountSdk`. ```tsx Get the SDK instance import { useBaseAccountSdk } from '@privy-io/react-auth'; diff --git a/docs/base-account/framework-integrations/privy/spend-permissions.mdx b/docs/base-account/framework-integrations/privy/spend-permissions.mdx index 51e29283..080e246a 100644 --- a/docs/base-account/framework-integrations/privy/spend-permissions.mdx +++ b/docs/base-account/framework-integrations/privy/spend-permissions.mdx @@ -1,39 +1,39 @@ --- -title: "Spend Permissions" -description: "Enable trusted spenders to move assets without additional signatures" +title: "Разрешения на траты" +description: "Включите доверенным сторонам возможность перемещать активы без дополнительных подписей" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx"; -Learn how to create and manage Spend Permissions that allow trusted spenders to move assets from Base Accounts without requiring additional user signatures. +Узнайте, как создавать и управлять Разрешениями на траты, которые позволяют доверенным сторонам перемещать активы из Base Accounts без необходимости дополнительных подписей пользователя. -## Overview +## Обзор -Spend Permissions enable users to grant timely allowances to trusted spenders, allowing them to move assets on behalf of the user within defined limits. This creates seamless user experiences for recurring payments, subscriptions, and automated transactions. +Разрешения на траты позволяют пользователям предоставлять своевременные лимиты доверенным сторонам, позволяя им перемещать активы от имени пользователя в рамках определенных ограничений. Это создает бесшовный пользовательский опыт для повторяющихся платежей, подписок и автоматизированных транзакций. -### What you'll achieve +### Что вы получите -By the end of this guide, you will: +К концу этого руководства вы сможете: -- Create Spend Permissions with specific allowances and time periods -- Fetch and manage existing Spend Permissions -- Use Spend Permissions to execute transactions -- Implement Spend Permission functionality in your React application +- Создавать Разрешения на траты с определенными лимитами и временными периодами +- Получать и управлять существующими разрешениями +- Использовать Разрешения на траты для выполнения транзакций +- Реализовать функциональность Разрешений на траты в вашем React-приложении -The code snippets in this guide are based on the following example project: +Фрагменты кода в этом руководстве основаны на следующем примере проекта: -## Setup +## Настройка -Follow the [Setup](/base-account/framework-integrations/privy/setup) guide to set up Privy with Base Account. +Следуйте руководству [настройки](/base-account/framework-integrations/privy/setup) чтобы настроить Privy с Base Account. -## Implementation +## Реализация -### Component Setup +### Настройка компонента ```tsx Spend Permissions Component (components/sections/spend-permissions.tsx) expandable @@ -57,11 +57,11 @@ export const SpendPermissions = () => { const [selectedPermission, setSelectedPermission] = useState(null); const [loading, setLoading] = useState(false); - // Configuration + // Конфигурация const spenderAddress = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"; const tokenAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base - // Find the Base Account wallet + // Находим кошелек Base Account const baseAccount = useMemo(() => { return wallets.find((wallet) => wallet.walletClientType === 'base_account'); }, [wallets]); @@ -118,7 +118,7 @@ export const SpendPermissions = () => { try { setLoading(true); - // Check permission status + // Проверяем статус разрешения const { isActive, remainingSpend } = await getPermissionStatus(selectedPermission); if (!isActive) { @@ -133,7 +133,7 @@ export const SpendPermissions = () => { return; } - // Prepare spend calls + // Подготавливаем вызовы для траты const spendCalls = await prepareSpendCallData(selectedPermission, spendAmount); console.log("Spend calls prepared:", spendCalls); @@ -152,25 +152,25 @@ export const SpendPermissions = () => { disabled={loading || !account} className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50" > - Create Spend Permission + Создать Разрешение на траты
- {/* Configuration display */} + {/* Отображение конфигурации */}

Configuration

@@ -180,7 +180,7 @@ export const SpendPermissions = () => {
- {/* Permissions list */} + {/* Список разрешений */} {permissions.length > 0 && (

Existing Permissions

@@ -211,11 +211,11 @@ export const SpendPermissions = () => { ``` -### Key Methods +### Ключевые методы -#### Creating Spend Permissions +#### Создание Разрешений на траты -Use `requestSpendPermission` to create new Spend Permissions: +Используйте `requestSpendPermission` для создания новых Разрешений на траты: ```tsx const permission = await requestSpendPermission({ @@ -224,14 +224,14 @@ const permission = await requestSpendPermission({ token: tokenAddress, chainId: base.id, allowance: BigInt(1) * BigInt(10 ** 6), // 1 USDC - periodInDays: 1, // 1 day + periodInDays: 1, // 1 день provider, }); ``` -#### Fetching Permissions +#### Получение разрешений -Use `fetchPermissions` to retrieve existing permissions: +Используйте `fetchPermissions` для получения существующих разрешений: ```tsx const permissions = await fetchPermissions({ @@ -242,49 +242,49 @@ const permissions = await fetchPermissions({ }); ``` -#### Using Permissions +#### Использование разрешений -Check permission status and prepare spend calls: +Проверьте статус разрешения и подготовьте вызовы для траты: ```tsx -// Check if permission is active +// Проверяем, активно ли разрешение const { isActive, remainingSpend } = await getPermissionStatus(permission); -// Prepare spend transaction data +// Подготавливаем данные транзакции для траты const spendCalls = await prepareSpendCallData(permission, spendAmount); ``` -### Configuration Options +### Параметры конфигурации -#### Allowance and Period +#### Лимит и период -Configure spending limits and time periods: +Настройте лимиты трат и временные периоды: ```tsx { allowance: BigInt(100) * BigInt(10 ** 6), // 100 USDC (6 decimals) - periodInDays: 7, // 7 days + periodInDays: 7, // 7 дней } ``` -#### Token Addresses +#### Адреса токенов -Common token addresses on Base: +Распространенные адреса токенов в сети Base: - **USDC**: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` - **ETH**: Native token `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` - **DAI**: `0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb` -### Use Cases +### Сценарии использования -Spend permissions are ideal for: +Разрешения на траты идеально подходят для: -- **Subscriptions**: Recurring payments without user interaction -- **DeFi protocols**: Automated trading and yield farming -- **Gaming**: In-game purchases and rewards -- **Commerce**: Streamlined checkout experiences +- **Подписок**: Повторяющиеся платежи без взаимодействия с пользователем +- **DeFi-протоколов**: Автоматизированная торговля и фарминг доходности +- **Игр**: Внутриигровые покупки и награды +- **Электронной коммерции**: Упрощенные процессы оформления заказа diff --git a/docs/base-account/framework-integrations/privy/sub-accounts.mdx b/docs/base-account/framework-integrations/privy/sub-accounts.mdx index dc6309ba..3ef966a4 100644 --- a/docs/base-account/framework-integrations/privy/sub-accounts.mdx +++ b/docs/base-account/framework-integrations/privy/sub-accounts.mdx @@ -1,47 +1,47 @@ --- -title: "Sub Accounts" -description: "Create and manage app-specific wallet accounts with Base Account" +title: "Субаккаунты" +description: "Создавайте и управляйте привязанными к приложению кошельковыми аккаунтами с помощью Base Account" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx"; -Learn how to create and manage Sub Accounts that provide app-specific wallet accounts embedded directly in your application. +Узнайте, как создавать и управлять субаккаунтами, которые предоставляют привязанные к приложению кошельковые аккаунты, встроенные непосредственно в ваше приложение. -## Overview +## Обзор -Sub Accounts allow you to provision dedicated wallet accounts for your users within your application. -These accounts are controlled by the user's main Base Account and provide an enhanced user experience -as the user's interactions produce no passkey prompts or popups. +Субаккаунты позволяют создавать выделенные кошельковые аккаунты для ваших пользователей в рамках вашего приложения. +Эти аккаунты управляются основным Base Account пользователя и обеспечивают улучшенный пользовательский опыт, +поскольку взаимодействие пользователя не вызывает запросов passkey или всплывающих окон. -Users can manage all their Sub Accounts at [account.base.app](https://account.base.app). +Пользователи могут управлять всеми своими субаккаунтами на [account.base.app](https://account.base.app). -If you would like to see a live demo of Sub Accounts in action, check out our [Sub Accounts Demo](https://sub-accounts-fc.vercel.app). +Если вы хотите увидеть работающую демонстрацию субаккаунтов, ознакомьтесь с нашей [демонстрацией субаккаунтов](https://sub-accounts-fc.vercel.app). -### What you'll achieve +### Что вы получите -By the end of this guide, you will: +К концу этого руководства вы сможете: -- Understand how Sub Accounts work with Base Account -- Create new Sub Accounts for users -- Retrieve and manage existing Sub Accounts -- Implement Sub Account in your Privy project +- Понять, как субаккаунты работают с Base Account +- Создавать новые субаккаунты для пользователей +- Получать и управлять существующими субаккаунтами +- Реализовать субаккаунты в вашем проекте с Privy -The code snippets in this guide are based on the following example project: +Фрагменты кода в этом руководстве основаны на следующем примере проекта: -## Setup +## Настройка -Follow the [Setup](/base-account/framework-integrations/privy/setup) guide to set up Privy with Base Account. +Следуйте руководству [настройки](/base-account/framework-integrations/privy/setup), чтобы настроить Privy с Base Account. -## Implementation +## Реализация -### Component Setup +### Настройка компонента ```tsx Sub Accounts Component (components/sections/sub-accounts.tsx) expandable @@ -61,7 +61,7 @@ const SubAccounts = () => { >([]); const [isLoading, setIsLoading] = useState(false); - // Find the Base Account wallet + // Находим кошелек Base Account const baseAccount = useMemo(() => { return wallets.find((wallet) => wallet.walletClientType === 'base_account'); }, [wallets]); @@ -71,11 +71,11 @@ const SubAccounts = () => { setIsLoading(true); try { - // Switch to Base Sepolia (or Base Mainnet - use 8453 for mainnet) + // Переключаемся на Base Sepolia (или Base Mainnet - используйте 8453 для mainnet) await baseAccount.switchChain(84532); const provider = await baseAccount.getEthereumProvider(); - // Get existing Sub Accounts + // Получаем существующие субаккаунты const response = await provider.request({ method: 'wallet_getSubAccounts', params: [{ @@ -98,11 +98,11 @@ const SubAccounts = () => { setIsLoading(true); try { - // Switch to Base Sepolia (or Base Mainnet - use 8453 for mainnet) + // Переключаемся на Base Sepolia (или Base Mainnet - используйте 8453 для mainnet) await baseAccount.switchChain(84532); const provider = await baseAccount.getEthereumProvider(); - // Create new Sub Account + // Создаем новый субаккаунт await provider.request({ method: 'wallet_addSubAccount', params: [{ @@ -117,7 +117,7 @@ const SubAccounts = () => { }] }); - // Refresh the Sub Accounts list + // Обновляем список субаккаунтов await handleGetSubAccounts(); } catch (error) { console.error("Error creating Sub Account:", error); @@ -134,14 +134,14 @@ const SubAccounts = () => { disabled={!baseAccount || isLoading} className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50" > - Get Sub Accounts + Получить субаккаунты
@@ -165,11 +165,11 @@ const SubAccounts = () => { ``` -### Key Methods +### Ключевые методы -#### Getting Sub Accounts +#### Получение субаккаунтов -Use `wallet_getSubAccounts` to retrieve existing Sub Accounts for a domain: +Используйте `wallet_getSubAccounts` для получения существующих субаккаунтов для домена: ```tsx Get Sub Accounts (components/sections/sub-accounts.tsx) const response = await provider.request({ @@ -181,9 +181,9 @@ const response = await provider.request({ }); ``` -#### Creating Sub Accounts +#### Создание субаккаунтов -Use `wallet_addSubAccount` to create new Sub Accounts: +Используйте `wallet_addSubAccount` для создания новых субаккаунтов: ```tsx Create Sub Account (components/sections/sub-accounts.tsx) await provider.request({ @@ -201,14 +201,14 @@ await provider.request({ }); ``` -### Network Configuration +### Конфигурация сети -Sub accounts work on both Base Mainnet and Base Sepolia: +Субаккаунты работают как в основной сети Base, так и в тестовой сети Base Sepolia: - **Base Mainnet**: Chain ID `8453` - **Base Sepolia**: Chain ID `84532` -### Explore further +### Узнать больше -- [Sub Accounts Guide](/base-account/improve-ux/sub-accounts) -- [Privy Sub Accounts Recipe](https://docs.privy.io/recipes/react/external-wallets/base-sub-accounts) \ No newline at end of file +- [Руководство по субаккаунтам](/base-account/improve-ux/sub-accounts) +- [Рецепт субаккаунтов Privy](https://docs.privy.io/recipes/react/external-wallets/base-sub-accounts) diff --git a/docs/base-account/framework-integrations/privy/wallet-actions.mdx b/docs/base-account/framework-integrations/privy/wallet-actions.mdx index 5d5d39cf..d1bf7dd3 100644 --- a/docs/base-account/framework-integrations/privy/wallet-actions.mdx +++ b/docs/base-account/framework-integrations/privy/wallet-actions.mdx @@ -1,34 +1,34 @@ --- -title: "Wallet Actions" -description: "Sign messages, transactions, and typed data with Privy wallets" +title: "Действия с кошельком" +description: "Подписывайте сообщения, транзакции и типизированные данные с помощью кошельков Privy" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx"; -Learn how to perform wallet actions including signing messages, typed data, and transactions for EVM wallets using Privy. +Узнайте, как выполнять действия с кошельком, включая подпись сообщений, типизированных данных и транзакций для EVM-кошельков с использованием Privy. -## Overview +## Обзор -Privy provides comprehensive [wallet action hooks](https://docs.privy.io/wallets/using-wallets/ethereum/send-a-transaction) that work seamlessly with EVM (Ethereum-compatible) wallets. You can sign messages, typed data, raw hashes, and transactions, as well as send transactions directly. +Privy предоставляет комплексные [хуки для действий с кошельком](https://docs.privy.io/wallets/using-wallets/ethereum/send-a-transaction), которые бесшовно работают с EVM (Ethereum-совместимыми) кошельками. Вы можете подписывать сообщения, типизированные данные, сырые хэши и транзакции, а также отправлять транзакции напрямую. -### What you'll achieve +### Что вы получите -By the end of this guide, you will: +К концу этого руководства вы сможете: -- Sign messages for EVM wallets -- Sign typed data (EIP-712) for structured data -- Send transactions on EVM networks +- Подписывать сообщения для EVM-кошельков +- Подписывать типизированные данные (EIP-712) для структурированных данных +- Отправлять транзакции в EVM-сетях -The code snippets in this guide are based on the following example project: +Фрагменты кода в этом руководстве основаны на следующем примере проекта: -## Implementation +## Реализация -### Component Setup +### Настройка компонента ```tsx Wallet Actions Component (components/sections/wallet-actions.tsx) expandable @@ -54,7 +54,7 @@ const [selectedWallet, setSelectedWallet] = useState<{ name: string; } | null>(null); - // Map wallets for selection + // Сопоставляем кошельки для выбора const allWallets = useMemo(() => { return wallets.map((wallet) => ({ address: wallet.address, @@ -169,28 +169,28 @@ const [selectedWallet, setSelectedWallet] = useState<{
- {/* Action Buttons */} + {/* Кнопки действий */}
@@ -199,9 +199,9 @@ const [selectedWallet, setSelectedWallet] = useState<{ ``` -### Wallet Actions +### Действия с кошельком -#### Sign Message +#### Подпись сообщения ```tsx Sign Message @@ -222,7 +222,7 @@ const handleSignMessage = async () => { ``` -#### Sign Typed Data (EIP-712) +#### Подпись типизированных данных (EIP-712) ```tsx Sign Typed Data expandable @@ -273,7 +273,7 @@ const handleSignTypedData = async () => { ``` -#### Send Transaction +#### Отправка транзакции ```tsx Send Transaction expandable @@ -296,8 +296,8 @@ const handleSendTransaction = async () => { ``` -## Explore further +## Узнать больше -- [Privy docs](https://docs.privy.io/) -- [Batch Transactions](/base-account/improve-ux/batch-transactions) -- [Sponsor Gas](/base-account/improve-ux/sponsor-gas/paymasters) \ No newline at end of file +- [Документация Privy](https://docs.privy.io/) +- [Пакетные транзакцииs](/base-account/improve-ux/batch-transactions) +- [Оплата газа (спонсорство)](/base-account/improve-ux/sponsor-gas/paymasters) diff --git a/docs/base-account/framework-integrations/rainbowkit.mdx b/docs/base-account/framework-integrations/rainbowkit.mdx index 800ce3af..9050ae4c 100644 --- a/docs/base-account/framework-integrations/rainbowkit.mdx +++ b/docs/base-account/framework-integrations/rainbowkit.mdx @@ -1,32 +1,32 @@ --- title: "RainbowKit" -description: "Integrate Base Account with RainbowKit" +description: "Интеграция Base Account с RainbowKit" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx"; -## Overview +## Обзор -[RainbowKit](https://www.rainbowkit.com/) is a React library that makes it easy to add wallet sign-in to your onchain application. It's designed to work out-of-the-box and includes native support for Base Account. +[RainbowKit](https://www.rainbowkit.com/) - это React-библиотека, которая упрощает добавление входа через кошельки в ваше ончейн-приложение. Она разработана для работы "из коробки" и включает нативную поддержку Base Account. -By integrating RainbowKit with Base Account, you can provide your users with a seamless onboarding experience while maintaining access to the full Base Account feature set. +Интегрируя RainbowKit с Base Account, вы можете предоставить пользователям бесшовный опыт подключения, сохраняя доступ ко всему набору функций Base Account. -### What you'll achieve +### Что вы получите -By the end of this guide, you will: +К концу этого руководства вы сможете: -* Set up RainbowKit with Base Account support -* Learn how to use both `ConnectButton` and `WalletButton` components -* Configure your app to prioritize Base Account as the primary wallet option -* Obtain and configure a Reown project ID (required for RainbowKit projects) +* Настроить RainbowKit с поддержкой Base Account +* Узнать, как использовать компоненты `ConnectButton` и `WalletButton` +* Настроить приложение для приоритетного использования Base Account как основного варианта кошелька +* Получить и настроить Reown Project ID (требуется для проектов с RainbowKit) -You can jump ahead and use the Base Account RainbowKit Template to get started: +Вы можете сразу перейти к использованию шаблона Base Account RainbowKit, чтобы начать работу: - + -## Installation +## Установка -After [creating a new Next.js project](https://nextjs.org/docs/app/getting-started/installation), install the required dependencies: +После [создания нового проекта Next.js](https://nextjs.org/docs/app/getting-started/installation), установите необходимые зависимости: ```bash npm @@ -47,79 +47,79 @@ After [creating a new Next.js project](https://nextjs.org/docs/app/getting-start -**Access the latest version of the Base Account SDK (Recommended)** +**Получите доступ к последней версии Base Account SDK (Рекомендуется)** -It is {HIGHLY RECOMMENDED} to access the latest version of the Base Account SDK in order to get the latest features and bug fixes. +It is {НАСТОЯТЕЛЬНО РЕКОМЕНДУЕТСЯ} получить доступ к последней версии Base Account SDK, чтобы получить последние функции и исправления ошибок. -To do this, you can use the following command to override it: +Для этого вы можете использовать следующую команду для переопределения версии: ```bash npm npm pkg set overrides.@base-org/account="latest" -# OR manually add to package.json: +# ИЛИ добавьте вручную в package.json: # "overrides": { "@base-org/account": "latest" } ``` ```bash pnpm -# pnpm requires manual addition to package.json: +# pnpm требует ручного добавления в package.json: # "pnpm": { "overrides": { "@base-org/account": "latest" } } ``` ```bash yarn -# yarn uses resolutions - add manually to package.json: +#yarn использует resolutions - добавьте вручную в package.json: # "resolutions": { "@base-org/account": "latest" } ``` ```bash bun -# bun supports overrides - add manually to package.json: +# bun поддерживает overrides - добавьте вручную в package.json: # "overrides": { "@base-org/account": "latest" } ``` -Or you can use a specific version by adding the version to the overrides: +Или вы можете использовать конкретную версию, добавив ее в `overrides`: ```bash npm npm pkg set overrides.@base-org/account="2.2.0" -# OR manually add to package.json: +# ИЛИ добавьте вручную в package.json: # "overrides": { "@base-org/account": "2.2.0" } ``` ```bash pnpm -# pnpm requires manual addition to package.json: +# pnpm требует ручного добавления в package.json: # "pnpm": { "overrides": { "@base-org/account": "2.2.0" } } ``` ```bash yarn -# yarn uses resolutions - add manually to package.json: +# yarn использует resolutions - добавьте вручную в package.json: # "resolutions": { "@base-org/account": "2.2.0" } ``` ```bash bun -# bun supports overrides - add manually to package.json: +# bun поддерживает overrides - добавьте вручную в package.json: # "overrides": { "@base-org/account": "2.2.0" } ``` -Make sure to delete your `node_modules` and `package-lock.json` and run a new install to ensure the overrides are applied. +Убедитесь, что удалили папку `node_modules` и файл `package-lock.json`, а затем выполните новую установку, чтобы переопределения применились. -## Get Your Reown Project ID +## Получите ваш Reown Project ID -Before you can use RainbowKit with Base Account, you need to obtain a project ID from Reown Cloud. +Прежде чем использовать RainbowKit с Base Account, вам необходимо получить Project ID из Reown Cloud. -1. Visit [Reown Cloud Dashboard](https://dashboard.reown.com/) -2. Sign up for a free account or log in if you already have one -3. Create a new project and copy the project ID. +1. Перейдите в [Reown Cloud Dashboard](https://dashboard.reown.com/) +2. Зарегистрируйте бесплатный аккаунт или войдите, если он уже есть +3. Создайте новый проект и скопируйте Project ID. -## Configuration +## Конфигурация -### 1. Configure Wagmi with RainbowKit +### 1. Настройте Wagmi с RainbowKit -Create a `wagmi.ts` file in your `src` directory to configure your blockchain connections and wallet options: +Создайте файл `wagmi.ts` в вашей директории `src`, чтобы настроить подключения к блокчейну и варианты кошельков: ```tsx src/wagmi.ts import { getDefaultConfig } from '@rainbow-me/rainbowkit'; @@ -130,36 +130,36 @@ import { export const config = getDefaultConfig({ appName: 'My Base Account App', - projectId: 'YOUR_PROJECT_ID', // Replace with your Reown project ID + projectId: 'YOUR_PROJECT_ID', // Замените на ваш Reown Project ID chains: [ mainnet, base ], - ssr: true, // Enable server-side rendering support + ssr: true, // Включите поддержку серверного рендеринга }); ``` - **Replace YOUR_PROJECT_ID** + **Замените YOUR_PROJECT_ID** - Make sure to replace `'YOUR_PROJECT_ID'` with the actual project ID you obtained from [Reown Cloud](https://dashboard.reown.com/). + Убедитесь, что заменили 'YOUR_PROJECT_ID' на фактический Project ID, полученный из [Reown Cloud](https://dashboard.reown.com/). - For production applications, use environment variables: + Для продакшен-приложений используйте переменные окружения: ```typescript projectId: process.env.NEXT_PUBLIC_REOWN_PROJECT_ID!, ``` - And add to your `.env.local`: + И добавьте в ваш `.env.local`: ```bash NEXT_PUBLIC_REOWN_PROJECT_ID=your_project_id_here ``` -### 2. Set up RainbowKit Provider +### 2. Настройте провайдер RainbowKit -Wrap your application with the necessary providers in your `_app.tsx`: +Оберните ваше приложение необходимыми провайдерами в вашем `_app.tsx`: ```tsx src/pages/_app.tsx import '../styles/global.css'; @@ -189,13 +189,13 @@ function MyApp({ Component, pageProps }: AppProps) { export default MyApp; ``` -## Usage +## Использование -RainbowKit provides two main components for wallet connections: `ConnectButton` and `WalletButton`. Both components support Base Account out of the box. +RainbowKit предоставляет два основных компонента для подключения кошельков: `ConnectButton` и `WalletButton`. Оба компонента поддерживают Base Account "из коробки". -### Option 1: Using ConnectButton +### Вариант 1: Использование ConnectButton -The `ConnectButton` is RainbowKit's all-in-one wallet connection component. It displays the wallet connection modal with all available wallets, including Base Account. +`ConnectButton` - это универсальный компонент RainbowKit для подключения кошельков. Он отображает модальное окно подключения кошелька со всеми доступными кошельками, включая Base Account. ```tsx src/pages/index.tsx import { ConnectButton } from '@rainbow-me/rainbowkit'; @@ -218,14 +218,14 @@ const Home: NextPage = () => { export default Home; ``` -When implemented, this is what it will look like: +При реализации это будет выглядеть так:
RainbowKit Wallet Window
-### Option 2: Using WalletButton for Base Account +### Вариант 2: Использование WalletButton для Base Account -The `WalletButton` component provides a direct connection to a specific wallet. This is ideal when you want to highlight Base Account as the primary wallet option. +Компонент `WalletButton` предоставляет прямое подключение к конкретному кошельку. Это идеально, когда вы хотите выделить Base Account в качестве основного варианта кошелька. ```tsx src/pages/index.tsx import { WalletButton } from '@rainbow-me/rainbowkit'; @@ -248,16 +248,16 @@ const Home: NextPage = () => { export default Home; ``` -When implemented, this is what it will look like: +При реализации это будет выглядеть так:
Base Account Button
-## Advanced Configuration +## Расширенная конфигурация -### Prioritize Base Account in Wallet List +### Приоритезация Base Account в списке кошельков -To make Base Account appear first in the wallet connection modal, you can customize the wallet order: +Чтобы Base Account отображался первым в модальном окне подключения кошелька, вы можете настроить порядок кошельков: ```tsx src/wagmi.ts import { getDefaultConfig } from '@rainbow-me/rainbowkit'; @@ -268,19 +268,19 @@ export const config = getDefaultConfig({ projectId: process.env.NEXT_PUBLIC_REOWN_PROJECT_ID!, chains: [base, mainnet, sepolia], ssr: true, - // Wallet configuration + // Конфигурация кошельков wallets: [ { groupName: 'Recommended', - wallets: ['baseAccount'], // Base Account appears first + wallets: ['baseAccount'], // Base Account отображается первым }, ], }); ``` -### Customize RainbowKit Theme +### Настройка темы RainbowKit -RainbowKit supports extensive theming options: +RainbowKit поддерживает расширенные возможности темизации: ```tsx src/pages/_app.tsx import { RainbowKitProvider, darkTheme } from '@rainbow-me/rainbowkit'; @@ -291,7 +291,7 @@ function MyApp({ Component, pageProps }: AppProps) { - Store sensitive configuration like your Reown project ID in environment variables, not in your code: + + Храните чувствительную конфигурацию, такую как ваш Reown Project ID, в переменных окружения, а не в коде: ```bash .env.local NEXT_PUBLIC_REOWN_PROJECT_ID=your_project_id_here ``` - - Always set `ssr: true` in your wagmi config for Next.js applications to avoid hydration issues: + + Всегда устанавливайте `ssr: true` в конфигурации wagmi для приложений Next.js, чтобы избежать проблем с гидратацией: ```typescript export const config = getDefaultConfig({ @@ -372,38 +372,38 @@ function NetworkSwitcher() { ``` - - Put Base as the first chain in your configuration to make it the default: + + Укажите Base первой сетью в вашей конфигурации, чтобы сделать ее сетью по умолчанию: ```typescript chains: [base, mainnet, ...otherChains] ``` - - Regularly update RainbowKit, wagmi, and viem to get the latest Base Account features and security patches: + + Регулярно обновляйте RainbowKit, wagmi и viem, чтобы получать последние функции Base Account и исправления безопасности: ```bash npm update @rainbow-me/rainbowkit wagmi viem ``` -## Next Steps +## Следующие шаги -Now that you have RainbowKit configured with Base Account, you can: +Теперь, когда у вас настроен RainbowKit с Base Account, вы можете: - - Learn more about Base Account and its features + + Узнайте больше о Base Account и его функциях - - Learn more about RainbowKit and its features + + Узнайте больше о RainbowKit и его функциях - - Learn more about wagmi and its features + + Узнайте больше о wagmi и его функциях - - Join the Base community and get help from other developers + + Присоединитесь к сообществу Base и получайте помощь от других разработчиков - \ No newline at end of file + diff --git a/docs/base-account/framework-integrations/wagmi/base-pay.mdx b/docs/base-account/framework-integrations/wagmi/base-pay.mdx index 55b02114..3889ef09 100644 --- a/docs/base-account/framework-integrations/wagmi/base-pay.mdx +++ b/docs/base-account/framework-integrations/wagmi/base-pay.mdx @@ -1,28 +1,28 @@ --- title: "Base Pay" -description: "Accept USDC payments with Base Pay in your Wagmi-powered React application" +description: "Принимайте платежи в USDC с помощью Base Pay в вашем React-приложении на Wagmi" --- -Base Pay works the same way in Wagmi applications as it does anywhere else - it operates independently of wallet connections and uses the Base Account SDK directly. +Base Pay работает в приложениях на Wagmi точно так же, как и везде - он функционирует независимо от подключений кошелька и использует Base Account SDK напрямую. -## Implementation +## Реализация -Base Pay doesn't require any special Wagmi integration. Simply follow the [Accept Payments guide](/base-account/guides/accept-payments) - all the code examples work exactly the same in your Wagmi app. +Для Base Pay не требуется какая-либо специальная интеграция с Wagmi. Просто следуйте [руководству по приему платежей (Accept Payments)](/base-account/guides/accept-payments) - все примеры кода работают точно так же и в вашем приложении на Wagmi. -The key points: +Ключевые моменты: -- **No wallet connection needed** - Base Pay handles everything through the SDK -- **Same API** - Use `pay()` and `getPaymentStatus()` exactly as shown in the main guide -- **Works alongside Wagmi** - You can display the user's connected address from `useAccount()` but it's not required for payments +- **Не требуется подключение кошелька** - Base Pay обрабатывает все через SDK +- **Тот же API** - Используйте `pay()` и `getPaymentStatus()` точно так, как показано в основном руководстве +- **Работает совместно с Wagmi** - Вы можете отображать подключенный адрес пользователя из `useAccount()`, но это не обязательно для платежей -## Quick Example +## Краткий пример ```tsx import { pay } from '@base-org/account' -import { useAccount } from 'wagmi' // Optional - just for display +import { useAccount } from 'wagmi' // Опционально - только для отображения export function CheckoutButton() { - const { address } = useAccount() // Optional + const { address } = useAccount() // Опционально const handlePayment = async () => { try { @@ -49,12 +49,12 @@ export function CheckoutButton() { ``` -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте руководству по бренду** -If you intend on using the `BasePayButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать BasePayButton, пожалуйста, следуйте [руководству по бренду](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. -## Learn More +## Узнать больше -For complete implementation details, examples, and advanced features like collecting user information, see the main [Accept Payments guide](/base-account/guides/accept-payments). +Полные детали реализации, примеры и расширенные функции, такие как сбор информации о пользователе, смотрите в основном [руководстве по приему платежей (Accept Payments)](/base-account/guides/accept-payments). diff --git a/docs/base-account/framework-integrations/wagmi/basenames.mdx b/docs/base-account/framework-integrations/wagmi/basenames.mdx index eca085f4..f6e7a333 100644 --- a/docs/base-account/framework-integrations/wagmi/basenames.mdx +++ b/docs/base-account/framework-integrations/wagmi/basenames.mdx @@ -1,21 +1,21 @@ --- title: "Basenames" -description: "Add support for Base names in your application using Wagmi and Viem" +description: "Добавьте поддержку имен Base (Basenames) в ваше приложение с помощью Wagmi и Viem" --- -## Overview +## Обзор -Basenames are human-readable names for addresses on Base. -They are built on top of the ENS protocol and comply with [ENSIP-19](https://docs.ens.domains/ensip/19/). -To learn more about Basenames, check out the [Basenames FAQ](/base-account/basenames/basenames-faq). +Basenames (имена Base) - это удобочитаемые имена для адресов в сети Base. +Они построены поверх протокола ENS и соответствуют [ENSIP-19](https://docs.ens.domains/ensip/19/). +Чтобы узнать больше о Basenames, ознакомьтесь с [часто задаваемыми вопросами о Basenames](/base-account/basenames/basenames-faq). -This guide will show you how to add support for Basenames to your application using [Viem](https://viem.sh/). +В этом руководстве показано, как добавить поддержку Basenames в ваше приложение с помощью [Viem](https://viem.sh/). -## Usage +## Использование -Use `getEnsName` to retrieve the primary ENS name for an address on Base: +Используйте `getEnsName`, чтобы получить основное ENS-имя для адреса в сети Base: ```ts import { createPublicClient, http, toCoinType } from 'viem' @@ -34,13 +34,13 @@ const name = await client.getEnsName({ -It is necessary to use a private RPC provider (`YOUR_PRIVATE_RPC_URL`) due to the computational demands associated with some of the ENSIP-19 resolution steps. +Необходимо использовать приватный RPC-провайдер (`YOUR_PRIVATE_RPC_URL`) из-за высоких вычислительных затрат, связанных с некоторыми шагами разрешения имен по спецификации ENSIP-19. -There may be some latency between the initial registration of a Basename and the ability to resolve this name via ENSIP-19 due to the slow production of state proofs necessary for trustless resolution. +Может возникать некоторая задержка между первоначальной регистрацией Basename и возможностью разрешить это имя через ENSIP-19 из-за медленного создания доказательств состояния, необходимых для разрешения имен без необходимости доверия. -[Learn more about getEnsName →](https://viem.sh/docs/ens/actions/getEnsName) +[Узнайте больше о getEnsName →](https://viem.sh/docs/ens/actions/getEnsName) diff --git a/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx b/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx index 24e25c47..b84a6be7 100644 --- a/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx +++ b/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx @@ -1,17 +1,17 @@ --- -title: "Other Use Cases" -description: "Access the Base Account provider from Wagmi for advanced functionality like Sub Accounts, Spend Permissions, and more" +title: "Другие варианты использования" +description: "Получите доступ к провайдеру Base Account из Wagmi для расширенной функциональности, такой как субаккаунты, разрешения на траты и многое другое" --- -Learn how to access the Base Account provider through Wagmi to unlock advanced Base Account features beyond basic authentication and payments. +Узнайте, как получить доступ к провайдеру Base Account через Wagmi, чтобы разблокировать расширенные функции Base Account, выходящие за рамки базовой аутентификации и платежей. -## Prerequisites +## Предварительные требования -Make sure you have [set up Wagmi with Base Account](/base-account/framework-integrations/wagmi/setup) before following this guide. +Перед тем как следовать этому руководству, убедитесь, что вы [настроили Wagmi с Base Account](/base-account/framework-integrations/wagmi/setup). -## Getting the Provider +## Получение провайдера -The key to accessing advanced Base Account functionality is getting the provider from your Wagmi connector. Once you have the provider, you can use any Base Account RPC method. +Ключом к доступу к расширенным функциям Base Account является получение провайдера из вашего коннектора Wagmi. Как только у вас есть провайдер, вы можете использовать любой RPC-метод Base Account. ```tsx Hook @@ -84,31 +84,31 @@ export function BaseAccountFeatures() { ``` -## Available Use Cases +## Доступные варианты использования -Once you have the provider, you can access all Base Account functionality: +Получив провайдер, вы можете получить доступ ко всей функциональности Base Account: -### Sub Accounts -Create and manage child accounts for improved UX. +### Субаккаунты +Создавайте дочерние аккаунты и управляйте ими для улучшения пользовательского опыта. -**Learn more:** [Sub Accounts Guide](/base-account/improve-ux/sub-accounts) | [Sub Accounts RPC Method](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount) +**Подробнее:** [Руководство по субаккаунтам](/base-account/improve-ux/sub-accounts) | [RPC-метод субаккаунтов](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount) -### Spend Permissions -Allow apps to spend on behalf of users with predefined limits. +### Разрешения на траты +Позволяйте приложениям тратить средства от имени пользователей в рамках предустановленных лимитов. -**Learn more:** [Spend Permissions Guide](/base-account/improve-ux/spend-permissions) | [Spend Permissions Reference](/base-account/reference/spend-permission-utilities/requestSpendPermission) +**Подробнее:** [Руководство по разрешениям на траты](/base-account/improve-ux/spend-permissions) | [Справочник по разрешениям на траты](/base-account/reference/spend-permission-utilities/requestSpendPermission) -### Batch Transactions -Execute multiple transactions in a single user confirmation. +### Пакетные транзакции +Выполняйте несколько транзакций при одном подтверждении пользователя. -**Learn more:** [Batch Transactions Guide](/base-account/improve-ux/batch-transactions) | [`wallet_sendCalls` Reference](/base-account/reference/core/provider-rpc-methods/wallet_sendCalls) +**Подробнее:** [Руководство по пакетным транзакциям](/base-account/improve-ux/batch-transactions) | [Справочник по `wallet_sendCalls`](/base-account/reference/core/provider-rpc-methods/wallet_sendCalls) -### Gasless Transactions -Sponsor gas fees for your users. +### Бесплатные транзакции +Оплачивайте комиссию газа за ваших пользователей. -**Learn more:** [Gasless Transactions Guide](/base-account/improve-ux/sponsor-gas/paymasters) | [Coinbase Developer Platform Paymaster](https://docs.cdp.coinbase.com/paymaster/introduction/welcome) +**Подробнее:** [Руководство по бесплатным транзакциям](/base-account/improve-ux/sponsor-gas/paymasters) | [Paymaster от Coinbase Developer Platform](https://docs.cdp.coinbase.com/paymaster/introduction/welcome) -### Full list of provider methods and capabilities -Access the full list of Base Account provider methods and capabilities. +### Полный список методов и возможностей провайдера +Получите доступ к полному списку методов и возможностей провайдера Base Account. -**Learn more:** [Provider RPC Methods](/base-account/reference/core/provider-rpc-methods/request-overview) | [Capabilities](/base-account/reference/core/capabilities/overview) \ No newline at end of file +**Подробнее:** [RPC-методы провайдера](/base-account/reference/core/provider-rpc-methods/request-overview) | [Возможности](/base-account/reference/core/capabilities/overview) diff --git a/docs/base-account/framework-integrations/wagmi/setup.mdx b/docs/base-account/framework-integrations/wagmi/setup.mdx index 5a58e9b8..fca54fea 100644 --- a/docs/base-account/framework-integrations/wagmi/setup.mdx +++ b/docs/base-account/framework-integrations/wagmi/setup.mdx @@ -1,23 +1,23 @@ --- -title: "Setup" -description: "Configure Wagmi with Base Account connector for your React application" +title: "Настройка" +description: "Настройте Wagmi с коннектором Base Account для вашего React-приложения" --- -Learn how to set up Wagmi with Base Account to enable Base Account SDK functionality with familiar React hooks. +Узнайте, как настроить Wagmi с Base Account, чтобы включить функциональность Base Account SDK с помощью знакомых React-хуков. -## Overview +## Обзор -[Wagmi](https://wagmi.sh/) is a collection of React hooks for Ethereum Virtual Machine (EVM) compatible networks that makes it easy to work with wallets, contracts, transactions, and signing. Base Account integrates perfectly with Wagmi, allowing you to use all your familiar hooks. +[Wagmi](https://wagmi.sh/) - это набор React-хуков для сетей, совместимых с Ethereum Virtual Machine (EVM), который упрощает работу с кошельками, контрактами, транзакциями и подписью. Base Account идеально интегрируется с Wagmi, позволяя использовать все знакомые хуки. -To create a new wagmi project, you can use the command line `npm create wagmi@latest`. +Чтобы создать новый проект с Wagmi, вы можете использовать команду `npm create wagmi@latest`. -## Installation +## Установка -If you start [a new wagmi project](https://wagmi.sh/react/getting-started), you can skip the installation step. +Если вы начинаете [новый проект с Wagmi](https://wagmi.sh/react/getting-started), вы можете пропустить шаг установки. -If you already have a project, you can install the dependencies with your package manager of choice: +Если у вас уже есть проект, вы можете установить зависимости с помощью вашего предпочтительного менеджера пакетов: ```bash npm @@ -38,24 +38,24 @@ bun add wagmi viem @base-org/account -To get access to the latest version of the Base Account SDK within Wagmi, you can use the following command to override it: +Чтобы получить доступ к последней версии Base Account SDK в рамках Wagmi, вы можете использовать следующую команду для ее переопределения: ```bash npm pkg set overrides.@base-org/account="latest" ``` -Or you can use a specific version by adding the version to the overrides: +Или вы можете использовать конкретную версию, добавив ее в `overrides`: ```bash npm pkg set overrides.@base-org/account="2.2.0" ``` -Make sure to delete your `node_modules` and `package-lock.json` and run a new install to ensure the overrides are applied. +Убедитесь, что удалили папку `node_modules` и файл `package-lock.json`, а затем выполните новую установку, чтобы переопределения применились. -## Configuration +## Конфигурация -### 1. Configure Wagmi with Base Account +### 1. Настройте Wagmi с Base Account -Create your Wagmi configuration with the Base Account connector configured for Base Account: +Создайте конфигурацию Wagmi с коннектором Base Account, настроенным для работы с Base Account: ```typescript // config/wagmi.ts @@ -77,9 +77,9 @@ export const config = createConfig({ }) ``` -### 2. Wrap Your App +### 2. Оберните ваше приложение -Wrap your application with the Wagmi provider: +Оберните ваше приложение провайдером Wagmi: ```tsx // app/layout.tsx or pages/_app.tsx @@ -100,9 +100,9 @@ export default function App({ children }: { children: React.ReactNode }) { } ``` -## Next Steps +## Следующие шаги -Now that you have Wagmi configured with Base Account, you can: +Теперь, когда у вас настроен Wagmi с Base Account, вы можете: -- [Connect users with Sign in with Base](/base-account/framework-integrations/wagmi/sign-in-with-base) -- [Access the Base Account provider](/base-account/framework-integrations/wagmi/other-use-cases) \ No newline at end of file +- [Подключать пользователей с помощью Sign in with Base](/base-account/framework-integrations/wagmi/sign-in-with-base) +- [Получить доступ к провайдеру Base Account](/base-account/framework-integrations/wagmi/other-use-cases) diff --git a/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx b/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx index 48fef435..1d9afc7a 100644 --- a/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx +++ b/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx @@ -1,42 +1,42 @@ --- -title: "Sign in with Base" -description: "Implement Base Account authentication using the proper SIWE flow with Wagmi" +title: "Вход через Base" +description: "Реализуйте аутентификацию Base Account, используя правильный поток SIWE с Wagmi" --- -Learn how to implement Sign in with Base using Wagmi by accessing the Base Account provider and following the proper SIWE (Sign-In With Ethereum) authentication flow. +Узнайте, как реализовать Sign in with Base с помощью Wagmi, получив доступ к провайдеру Base Account и следуя правильному потоку аутентификации SIWE (Sign-In With Ethereum). -## Prerequisites +## Предварительные требования -Make sure you have [set up Wagmi with Base Account](/base-account/framework-integrations/wagmi/setup) before following this guide. +Перед тем как следовать этому руководству, убедитесь, что вы [настроили Wagmi с Base Account](/base-account/framework-integrations/wagmi/setup). -## Overview +## Обзор -To implement Sign in with Base with Wagmi, you need to: +Чтобы реализовать Sign in with Base с Wagmi, вам необходимо: -1. Get the Base Account connector from Wagmi -2. Access the underlying provider from the connector -3. Use `wallet_connect` with `signInWithEthereum` capabilities -4. Verify the signature on your backend +1. Получить коннектор Base Account из Wagmi +2. Получить доступ к базовому провайдеру из коннектора +3. Использовать `wallet_connect` с возможностями `signInWithEthereum` +4. Проверить подпись на вашем бэкенде -This follows the same flow as shown in the [authenticate users guide](/base-account/guides/authenticate-users), but integrates with Wagmi's connector system. +Этот процесс соответствует тому же потоку, что показан в [руководстве по аутентификации пользователей](/base-account/guides/authenticate-users), но интегрируется с системой коннекторов Wagmi. -To get access to the latest version of the Base Account SDK within Wagmi, you can use the following command to override it: +Чтобы получить доступ к последней версии Base Account SDK в рамках Wagmi, вы можете использовать следующую команду для ее переопределения: ```bash npm pkg set overrides.@base-org/account="latest" ``` -Or you can use a specific version by adding the version to the overrides: +Или вы можете использовать конкретную версию, добавив ее в `overrides`: ```bash npm pkg set overrides.@base-org/account="2.2.0" ``` -Make sure to delete your `node_modules` and `package-lock.json` and run a new install to ensure the overrides are applied. +Убедитесь, что удалили папку `node_modules` и файл `package-lock.json`, а затем выполните новую установку, чтобы переопределения применились. -## Implementation +## Реализация -### Code Snippets +### Примеры кода ```ts Browser (Wagmi + SDK) @@ -51,7 +51,7 @@ export function SignInWithBase() { const { connectAsync, connectors } = useConnect() const { disconnect } = useDisconnect() - // Find the Base Account connector + // Находим коннектор Base Account const baseAccountConnector = connectors.find( connector => connector.id === 'baseAccount' ) @@ -66,16 +66,16 @@ export function SignInWithBase() { setError(null) try { - // 1 — get a fresh nonce (generate locally or prefetch from backend) + // 1 - получаем свежий nonce (генерируем локально или предварительно загружаем с бэкенда) const nonce = window.crypto.randomUUID().replace(/-/g, '') - // OR prefetch from server + // ИЛИ предзагружаем с сервера // const nonce = await fetch('/auth/nonce').then(r => r.text()) - // 2 — connect and get the provider + // 2 - подключаемся и получаем провайдер await connectAsync({ connector: baseAccountConnector }) const provider = baseAccountConnector.provider - // 3 — authenticate with wallet_connect + // 3 - аутентифицируемся с помощью wallet_connect const authResult = await provider.request({ method: 'wallet_connect', params: [{ @@ -93,7 +93,7 @@ export function SignInWithBase() { const { address, capabilities } = accounts[0] const { message, signature } = capabilities.signInWithEthereum - // 4 — verify on backend + // 4 - проверяем на бэкенде await fetch('/auth/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -133,15 +133,15 @@ export async function verifySig(req, res) { const { address, message, signature } = req.body; const valid = await client.verifyMessage({ address, message, signature }); if (!valid) return res.status(401).json({ error: 'Invalid signature' }); - // create session / JWT + // создаем сессию / JWT res.json({ ok: true }); } ``` -### 3. Using the Pre-built Button Component +### 3. Использование готового компонента кнопки -You can also use the official [Sign In With Base](/base-account/reference/ui-elements/sign-in-with-base-button) button component: +Вы также можете использовать официальный компонент кнопки [Sign In With Base](/base-account/reference/ui-elements/sign-in-with-base-button): ```tsx // components/SignInButton.tsx @@ -159,14 +159,14 @@ export function SignInButton() { if (!baseAccountConnector) return try { - // Generate nonce + // Генерируем nonce const nonce = window.crypto.randomUUID().replace(/-/g, '') - // Connect and get provider + // Подключаемся и получаем провайдер await connectAsync({ connector: baseAccountConnector }) const provider = baseAccountConnector.provider - // Perform SIWE authentication + // Выполняем аутентификацию SIWE const authResult = await provider.request({ method: 'wallet_connect', params: [{ @@ -180,12 +180,12 @@ export function SignInButton() { }] }) - // Extract and verify signature + // Извлекаем и проверяем подпись const { accounts } = authResult const { address, capabilities } = accounts[0] const { message, signature } = capabilities.signInWithEthereum - // Send to backend for verification + // Отправляем на бэкенд для проверки await fetch('/auth/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -206,8 +206,8 @@ export function SignInButton() { ``` -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте руководству по бренду** -If you intend on using the `SignInWithBaseButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать SignInWithBaseButton, пожалуйста, следуйте [руководству по Бренду](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. - \ No newline at end of file +
diff --git a/docs/base-account/framework-integrations/wagmi/sub-accounts.mdx b/docs/base-account/framework-integrations/wagmi/sub-accounts.mdx index 1179eab2..335ef508 100644 --- a/docs/base-account/framework-integrations/wagmi/sub-accounts.mdx +++ b/docs/base-account/framework-integrations/wagmi/sub-accounts.mdx @@ -1,23 +1,23 @@ --- -title: "Using Sub Accounts" -description: "Implement Base Account Sub Accounts using Wagmi" +title: "Использование субаккаунтов" +description: "Реализуйте субаккаунты Base Account с помощью Wagmi" --- -Learn how to create and manage Sub Accounts using Wagmi hooks and Base Account provider methods. +Узнайте, как создавать субаккаунты и управлять ими с помощью хуков Wagmi и методов провайдера Base Account. -## Prerequisites +## Предварительные требования -Make sure you have: -- [Set up Wagmi with Base Account](/base-account/framework-integrations/wagmi/setup) -- [Implemented Sign in with Base](/base-account/framework-integrations/wagmi/sign-in-with-base) +Убедитесь, что вы: +- [Настроили Wagmi с Base Account](/base-account/framework-integrations/wagmi/setup) +- [Реализовали Sign in with Base](/base-account/framework-integrations/wagmi/sign-in-with-base) -## Overview +## Обзор -Sub Accounts allow you to create child accounts that can spend from the parent account's balance using [Spend Permissions](/base-account/improve-ux/spend-permissions). This reduces the need for frequent user signatures and improves the user experience. +Субаккаунты позволяют создавать дочерние аккаунты, которые могут тратить средства с баланса родительского аккаунта, используя [Разрешения на траты (Spend Permissions)](/base-account/improve-ux/spend-permissions). Это снижает потребность в частых подписях пользователя и улучшает пользовательский опыт. -## Creating Sub Accounts +## Создание субаккаунтов -Use the Base Account provider to create Sub Accounts: +Используйте провайдер Base Account для создания субаккаунтов: ```tsx import { useAccount, useConnector } from 'wagmi' @@ -36,7 +36,7 @@ export function CreateSubAccount() { try { const provider = connector.provider - // Create a new Sub Account + // Создаем новый субаккаунт const result = await provider?.request({ method: 'wallet_addSubAccount', params: [{ @@ -81,9 +81,9 @@ export function CreateSubAccount() { } ``` -## Listing Sub Accounts +## Получение списка субаккаунтов -Retrieve existing Sub Accounts for the connected wallet: +Получите существующие субаккаунты для подключенного кошелька: ```tsx import { useAccount, useConnector } from 'wagmi' @@ -162,9 +162,9 @@ export function SubAccountsList() { } ``` -## Using Sub Accounts for Transactions +## Использование субаккаунтов для транзакций -Once you have Sub Accounts, you can use them to perform transactions: +Получив субаккаунты, вы можете использовать их для выполнения транзакций: ```tsx import { useAccount, useConnector, useWriteContract } from 'wagmi' @@ -183,13 +183,13 @@ export function SubAccountTransactions() { try { const provider = connector.provider - // Send transaction using Sub Account + // Отправляем транзакцию с использованием субаккаунта const result = await provider?.request({ method: 'wallet_sendCalls', params: [{ version: '1.0', chainId: `0x${Number(8453).toString(16)}`, - from: selectedSubAccount, // Use Sub Account as sender + from: selectedSubAccount, //Используем субаккаунт как отправителя calls: [{ to: '0x...' as `0x${string}`, value: '0x0', @@ -233,9 +233,9 @@ export function SubAccountTransactions() { } ``` -## Complete Example +## Полный пример -Here's a complete component that combines all Sub Account functionality: +Вот полный компонент, объединяющий всю функциональность работы с субаккаунтами: ```tsx import { useAccount, useConnector } from 'wagmi' @@ -289,7 +289,7 @@ export function SubAccountManager() { }) if (result?.subAccount) { - // Refresh the list + // Обновляем список await fetchSubAccounts() } } catch (error) { @@ -359,8 +359,8 @@ export function SubAccountManager() { } ``` -## Learn More +## Узнать больше -- [Sub Accounts overview](/base-account/improve-ux/sub-accounts) -- [Spend Permissions](/base-account/improve-ux/spend-permissions) -- [Base Account RPC methods](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount) +- [Обзор субаккаунтов](/base-account/improve-ux/sub-accounts) +- [Разрешения на траты](/base-account/improve-ux/spend-permissions) +- [RPC-методы Base Account](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount) diff --git a/docs/base-account/guides/accept-payments.mdx b/docs/base-account/guides/accept-payments.mdx index 588390ad..48b0f0a6 100644 --- a/docs/base-account/guides/accept-payments.mdx +++ b/docs/base-account/guides/accept-payments.mdx @@ -1,49 +1,49 @@ --- -title: "Accept Payments" -description: "Add one-tap USDC payments to your app with the pay() helper and Base Pay Button." +title: "Прием платежей" +description: "Добавьте оплату USDC в одно нажатие в ваше приложение с помощью функции-помощника pay() и кнопки Base Pay Button." --- import {BasePayButton} from "/snippets/BasePayButton.mdx" import {SignInWithBaseButton} from "/snippets/SignInWithBaseButton.mdx" -## Why Base Pay? +## Почему Base Pay? -USDC on Base is a fully-backed digital dollar that settles in seconds and costs pennies in gas. Base Pay lets you accept those dollars with a single click—no cards, no FX fees, no chargebacks. +USDC в сети Base - это полностью обеспеченная цифровая валюта, эквивалентная доллару, которая обрабатывается за секунды и стоит копейки в виде комиссии газа. Base Pay позволяет принимать эти доллары одним щелчком мыши — без банковских карт, без комиссий за конвертацию валют, без отзывов платежей (чарджбэков). -* **Any user can pay** – works with every Base Account (smart-wallet) out of the box. -* **USDC, not gas** – you charge in dollars; gas sponsorship is handled automatically. -* **Fast** – most payments confirm in <2 seconds on Base. -* **Funded accounts** – users pay with USDC from their Base Account or Coinbase Account. -* **No extra fees** – you receive the full amount. +* **Может платить любой пользователь** – работает с любым Base Account (смарт-кошельком) сразу после подключения. +* **USDC, а не gas** – вы выставляете счет в долларах; спонсорская оплата газа обрабатывается автоматически. +* **Быстро** – большинство платежей подтверждается менее чем за 2 секунды в сети Base. +* **Пополненные счета** – пользователи платят USDC со своего Base Account или Coinbase Account. +* **Без дополнительных комиссий** – вы получаете полную сумму. -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте руководству по бренду** -If you intend on using the BasePayButton, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать BasePayButton, пожалуйста, следуйте [руководству по Бренду](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. -## Client-side (Browser SDK) +## Клиентская часть (Browser SDK) -**Interactive Playground:** Try out the `pay()` and `getPaymentStatus()` functions in our [Base Pay SDK Playground](https://base.github.io/account-sdk/pay-playground) before integrating them into your app. +**Интерактивная песочница:** Попробуйте функции `pay()` и `getPaymentStatus()` в нашей [песочнице Base Pay SDK](https://base.github.io/account-sdk/pay-playground) перед их интеграцией в ваше приложение. ```ts Browser (SDK) import { pay, getPaymentStatus } from '@base-org/account'; -// Trigger a payment – user will see a popup from their wallet service +// Инициируем платеж – пользователь увидит всплывающее окно от своего сервиса кошелька try { const payment = await pay({ - amount: '1.00', // USD amount (USDC used internally) - to: '0xRecipient', // your address - testnet: true // set false for Mainnet + amount: '1.00', // Сумма в USD (внутренне используется USDC) + to: '0xRecipient', // ваш адрес получателя + testnet: true // установите false для Mainnet }); - // Option 1: Poll until mined + // Вариант 1: Опрашиваем статус до включения в блок (mined) const { status } = await getPaymentStatus({ id: payment.id, - testnet: true // MUST match the testnet setting used in pay() + testnet: true // ДОЛЖНО совпадать с настройкой testnet, использованной в pay() }); if (status === 'completed') console.log('🎉 payment settled'); @@ -53,18 +53,18 @@ try { ``` -**Important:** The `testnet` parameter in `getPaymentStatus()` must match the value used in the original `pay()` call. If you initiated a payment on testnet with `testnet: true`, you must also pass `testnet: true` when checking its status. +**Важно:** Параметр testnet в `getPaymentStatus()` должен совпадать со значением, использованным в исходном вызове `pay()`. Если вы инициировали платеж в тестовой сети с `testnet: true`, вы также должны передать `testnet: true` при проверке его статуса. -This is what the user will see when prompted to pay: +Вот что увидит пользователь, когда его попросят оплатить:
Pay Popup
-### Collect user information (optional) +### Сбор информации о пользователе (опционально) -Need an email, phone, or shipping address at checkout? Pass a payerInfo object: +Нужна электронная почта, телефон или адрес доставки при оформлении заказа? Передайте объект payerInfo: ```ts try { @@ -77,13 +77,13 @@ try { { type: 'phoneNumber', optional: true }, { type: 'physicalAddress', optional: true } ], - callbackURL: 'https://your-api.com/validate' // Optional - for server-side validation + callbackURL: 'https://your-api.com/validate' // Опционально - для проверки на стороне сервера } }); console.log(`Payment sent! Transaction ID: ${payment.id}`); - // Log the collected user information + // Логируем собранную информацию о пользователе if (payment.payerInfoResponses) { if (payment.payerInfoResponses.email) { console.log(`Email: ${payment.payerInfoResponses.email}`); @@ -102,27 +102,27 @@ try { } ``` -Supported request types: +Поддерживаемые типы запросов: -| type | returns | +| тип | возвращает | |---------|---------| | email | string | | name | { firstName, familyName } | | phoneNumber | { number, country } | -| physicalAddress | [full address object](/base-account/reference/core/capabilities/datacallback#physical-address-object) | +| physicalAddress | [полный объект адреса](/base-account/reference/core/capabilities/datacallback#physical-address-object) | | onchainAddress | string | -Required by default — set optional: true to avoid aborting the payment if the user declines. +<Предупреждение>Обязательно по умолчанию — установите optional: true, чтобы платеж не прерывался, если пользователь откажется предоставлять данные. -**How to validate the user's information?** +**Как проверить информацию пользователя?** -You can use the `callbackURL` to validate the user's information on the server side. +Вы можете использовать `callbackURL` для проверки информации пользователя на стороне сервера. -Learn more about this in the [callbackURL reference](/base-account/reference/core/capabilities/datacallback). +Узнайте больше об этом в [справочнике callbackURL](/base-account/reference/core/capabilities/datacallback). -## Polling example +## Пример опроса статуса ```ts Backend (SDK) import { getPaymentStatus } from '@base-org/account'; @@ -130,17 +130,17 @@ import { getPaymentStatus } from '@base-org/account'; export async function checkPayment(txId, testnet = false) { const status = await getPaymentStatus({ id: txId, - testnet // Must match the testnet setting from the original pay() call + testnet //Должно совпадать с настройкой testnet из исходного вызова pay() }); if (status.status === 'completed') { - // fulfil order + // исполняем заказ } } ``` -## Add the Base Pay Button +## Добавьте кнопку Base Pay -Use the pre-built component for a native look-and-feel: +Используйте готовый компонент для нативного внешнего вида и поведения: ```tsx title="Checkout.tsx" import { BasePayButton } from '@base-org/account-ui/react'; @@ -165,18 +165,18 @@ export function Checkout() { } ``` -See full props and theming options in the [Button Reference](/base-account/reference/ui-elements/base-pay-button) and [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines). +Полный список пропсов и параметров темизации смотрите в [Button справочнике](/base-account/reference/ui-elements/base-pay-button) и [Руководстве по бренду](/base-account/reference/ui-elements/brand-guidelines). -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте руководству по бренду** -If you intend on using the BasePayButton, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать BasePayButton, пожалуйста, следуйте [руководству по Бренду](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. -## Test on Base Sepolia +## Тестирование в сети Base Sepolia -1. Get test USDC from the Circle Faucet (select "Base Sepolia"). -2. Pass testnet: true in your pay() and getPaymentStatus() calls. -3. Use Sepolia BaseScan to watch the transaction. +1. Получите тестовые USDC на Circle Faucet (select "Base Sepolia"). +2. Передайте testnet: trueв ваши вызовыpay() и getPaymentStatus(). +3. Используйте Sepolia BaseScan чтобы отслеживать транзакцию. - \ No newline at end of file + diff --git a/docs/base-account/guides/accept-recurring-payments.mdx b/docs/base-account/guides/accept-recurring-payments.mdx index 38e6461e..50b0dac3 100644 --- a/docs/base-account/guides/accept-recurring-payments.mdx +++ b/docs/base-account/guides/accept-recurring-payments.mdx @@ -1,105 +1,105 @@ --- -title: "Accept Recurring Payments" -description: "Enable subscription-based revenue models with automatic USDC payments" +title: "Прием повторяющихся платежей" +description: "Включите модели дохода на основе подписок с автоматическими платежами в USDC" --- import {BasePayButton} from "/snippets/BasePayButton.mdx" import {SignInWithBaseButton} from "/snippets/SignInWithBaseButton.mdx" -## Start accepting recurring payments with Base Pay Subscriptions +## Начните принимать повторяющиеся платежи с помощью Base Pay Subscriptions -Base Subscriptions enable you to build predictable, recurring revenue streams by accepting automatic USDC payments. Whether you're running a SaaS platform, content subscription service, or any business model requiring regular payments, Base Subscriptions provide a seamless solution with no merchant fees. +Base Subscriptions позволяют создавать предсказуемые, повторяющиеся потоки доходов, принимая автоматические платежи в USDC. Независимо от того, управляете ли вы SaaS-платформой, сервисом подписки на контент или любой другой бизнес-моделью, требующей регулярных платежей, Base Subscriptions предоставляют бесшовное решение без комиссий для мерчантов. -**Key Capabilities:** +**Ключевые возможности:** - -Support any billing cycle that fits your business model: -- Daily subscriptions for short-term services -- Weekly for regular deliveries or services -- Monthly for standard SaaS subscriptions -- Annual for discounted long-term commitments -- Custom periods (e.g., 14 days, 90 days) for unique models + +Поддержка любого цикла оплаты, подходящего для вашей бизнес-модели: +- Ежедневные подписки для краткосрочных услуг +- Еженедельные для регулярных поставок или услуг +- Ежемесячные для стандартных SaaS-подписок +- Годовые для долгосрочных обязательств со скидкой +- Пользовательские периоды (например, 14 дней, 90 дней) для уникальных моделей - -Charge any amount up to the permitted limit: -- Fixed recurring amounts for predictable billing -- Variable usage-based charges within a cap -- Tiered pricing with different charge amounts -- Prorated charges for mid-cycle changes + +Списание любой суммы в пределах разрешенного лимита: +- Фиксированные повторяющиеся суммы для предсказуемого биллинга +- Переменные платежи на основе использования в пределах лимита +- Многоуровневое ценообразование с разными суммами списания +- Пропорциональные платежи за изменения в середине цикла - -Full control over the subscription lifecycle: -- Real-time status checking to verify active subscriptions -- Remaining charge amount for the current period -- Next period start date for planning -- Cancellation detection for immediate updates + +Полный контроль над жизненным циклом подписки: +- Проверка статуса в реальном времени для подтверждения активных подписок +- Оставшаяся сумма к списанию в текущем периоде +- Дата начала следующего периода для планирования +- Обнаружение отмены для немедленного обновления - -Built for production use cases: -- No transaction fees or platform cuts -- Instant settlement in USDC stablecoin -- Testnet support for development and testing -- Detailed transaction history for accounting -- Programmatic access via SDK + +Созданы для рабочих сценариев: +- Отсутствие комиссий за транзакции или платформенных отчислений +- Мгновенное завершение расчетов в стейблкоине USDC +- Поддержка тестовой сети (testnet) для разработки и тестирования +- Подробная история транзакций для бухгалтерии +- Программный доступ через SDK -## How It Works +## Как это работает -Base Subscriptions leverage **Spend Permissions** – a powerful onchain primitive that allows users to grant revocable spending rights to applications. Here's the complete flow: +Base Subscriptions используют **Разрешения на траты** - мощную ончейн-примитив, которая позволяет пользователям предоставлять приложениям отзывные права на списание средств. Вот полная схема работы: - -Your customer grants your application permission to charge their wallet up to a specified amount each billing period. This is a one-time approval that remains active until cancelled. + +Ваш клиент предоставляет вашему приложению разрешение на списание средств с его кошелька до определенной суммы за каждый расчетный период. Это одноразовое подтверждение, которое остается активным до отмены. - -Your backend service charges the subscription when payment is due, without requiring any user interaction. You can charge up to the approved amount per period. + +Ваш бэкенд-сервис списывает средства по подписке, когда наступает срок платежа, без необходимости какого-либо взаимодействия с пользователем. Вы можете списывать средства до утвержденной суммы за период. - -The spending limit automatically resets at the start of each new period. If you don't charge the full amount in one period, it doesn't roll over. + +Лимит трат автоматически сбрасывается в начале каждого нового периода. Если вы не списали полную сумму в одном периоде, она не переносится на следующий. - -Customers can view and cancel their subscriptions anytime through their wallet, ensuring transparency and trust. + +лиенты могут просматривать и отменять свои подписки в любое время через свой кошелек, что обеспечивает прозрачность и доверие. -## Implementation Guide +## Руководство по реализации -### Architecture Overview +### Обзор архитектуры -A complete subscription implementation requires both client and server components: +Полная реализация подписок требует как клиентских, так и серверных компонентов: -**Client-Side (Frontend):** -- User interface for subscription creation -- Create wallet requests and handle user responses +**Клиентская часть (Фронтенд):** +- Пользовательский интерфейс для создания подписки +- Создание запросов к кошельку и обработка ответов пользователя -**Server-Side (Backend):** -- Wallet for executing charges -- Scheduled jobs for periodic billing -- Database for subscription tracking -- Handlers for status updates -- Retry logic for failed charges +**Серверная часть (Бэкенд):** +- Кошелек для выполнения списаний +-Запланированные задачи для периодического биллинга +- База данных для отслеживания подписок +- Обработчики обновлений статуса +- Логика повторов для неудачных списаний -**Security Requirements** +**Требования безопасности** -To accept recurring payments, you need: -1. A dedicated wallet address to act as the subscription owner (spender) -2. Backend infrastructure to execute charges securely -3. Database to store and manage subscription IDs -4. Never expose private keys in client-side code +Для приема повторяющихся платежей вам необходимо: +1. Выделенный адрес кошелька, который будет выступать в роли владельца подписки +2. Бэкенд-инфраструктура для безопасного выполнения списаний +3. База данных для хранения и управления ID подписок +4. Никогда не раскрывайте приватные ключи в клиентском коде -### Client-Side: Create Subscriptions +### Клиентская часть: Создание подписок -Users create subscriptions from your frontend application: +Пользователи создают подписки из вашего фронтенд-приложения: ```tsx SubscriptionButton.tsx expandable import React, { useState } from 'react'; @@ -114,22 +114,22 @@ export function SubscriptionButton() { setLoading(true); try { - // Create subscription + // Создаем подписку const subscription = await base.subscription.subscribe({ recurringCharge: "29.99", - subscriptionOwner: "0xYourAppWallet", // Replace with your wallet address + subscriptionOwner: "0xYourAppWallet", // Замените на адрес вашего кошелька periodInDays: 30, testnet: false }); - // Store subscription ID for future reference + // Сохраняем ID подписки для дальнейшего использования setSubscriptionId(subscription.id); console.log('Subscription created:', subscription.id); console.log('Payer:', subscription.subscriptionPayer); console.log('Amount:', subscription.recurringCharge); console.log('Period:', subscription.periodInDays, 'days'); - // Send subscription ID to your backend + // Отправляем ID подписки на ваш бэкенд await saveSubscriptionToBackend(subscription.id, subscription.subscriptionPayer); setSubscribed(true); @@ -143,7 +143,7 @@ export function SubscriptionButton() { }; const saveSubscriptionToBackend = async (id: string, payer: string) => { - // Example API call to store subscription in your database + // Пример API-вызова для сохранения подписки в вашей базе данных const response = await fetch('/api/subscriptions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -176,17 +176,17 @@ export function SubscriptionButton() { } ``` -### Server-Side: Charge Subscriptions +### Серверная часть: Списание по подпискам -Execute charges from your backend service that controls the subscription owner wallet: +Выполняйте списания из вашего бэкенд-сервиса, который контролирует кошелек владельца подписки: ```typescript chargeSubscriptions.ts expandable import { base } from '@base-org/account'; import { createWalletClient, http } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { base as baseChain } from 'viem/chains'; -// Initialize wallet client with your subscription owner account -const account = privateKeyToAccount('0x...'); // Your app's private key +// Инициализируем клиент кошелька с учетной записью владельца подписки +const account = privateKeyToAccount('0x...'); // Приватный ключ вашего приложения const walletClient = createWalletClient({ account, chain: baseChain, @@ -195,7 +195,7 @@ const walletClient = createWalletClient({ async function chargeSubscription(subscriptionId: string) { try { - // 1. Check subscription status + // 1. Проверяем статус подписки const status = await base.subscription.getStatus({ id: subscriptionId, testnet: false @@ -213,16 +213,16 @@ const status = await base.subscription.getStatus({ return { success: false, reason: 'no_charge_available' }; } - // 2. Prepare charge transaction for max available amount + // 2. Подготавливаем транзакцию списания на максимальную доступную сумму const chargeCalls = await base.subscription.prepareCharge({ id: subscriptionId, amount: 'max-remaining-charge', testnet: false }); - // 3. Execute each charge call using standard sendTransaction - // Note: prepareCharge may return multiple calls (e.g., approval + transfer) - // We execute them sequentially to ensure proper ordering + // 3. Выполняем каждый вызов списания с помощью стандартного sendTransaction + // Примечание: prepareCharge может вернуть несколько вызовов (например, approval + transfer) + // Мы выполняем их последовательно, чтобы обеспечить правильный порядок const transactionHashes = []; for (const call of chargeCalls) { @@ -234,7 +234,7 @@ const status = await base.subscription.getStatus({ transactionHashes.push(hash); - // Wait for transaction confirmation before next call + // Ждем подтверждения транзакции перед следующим вызовом await walletClient.waitForTransactionReceipt({ hash }); } @@ -255,31 +255,31 @@ const status = await base.subscription.getStatus({ } ``` -**Private Key Security** +**Безопасность приватного ключа** -Never expose your subscription owner private key +Никогда не раскрывайте приватный ключ владельца подписки. -### Testing on Testnet +### Тестирование в тестовой сети -Test your subscription implementation on Base Sepolia before going live: +Протестируйте вашу реализацию подписок в сети Base Sepolia перед запуском в рабочую сеть: ```typescript testnet.ts expandable -// Use testnet for development +// Используйте тестовую сеть для разработки const subscription = await base.subscription.subscribe({ recurringCharge: "10.00", subscriptionOwner: "0xTestWallet", - periodInDays: 1, // Daily for faster testing - testnet: true // Use Base Sepolia + periodInDays: 1, // Ежедневно для более быстрого тестирования + testnet: true // Используем Base Sepolia }); -// Check status on testnet +// Проверяем статус в тестовой сети const status = await base.subscription.getStatus({ id: subscription.id, testnet: true }); -// Prepare charge on testnet +// Подготавливаем списание в тестовой сети const calls = await base.subscription.prepareCharge({ id: subscription.id, amount: "10.00", @@ -287,19 +287,19 @@ const calls = await base.subscription.prepareCharge({ }); ``` -## Network Support +## Поддержка сетей -| Network | Chain ID | Status | +| Сеть | Chain ID | Статус | |---------|----------|--------| -| Base Mainnet | 8453 | ✅ Production Ready | -| Base Sepolia | 84532 | ✅ Testing Available | +| Base Mainnet | 8453 | ✅ Готово для продакшена | +| Base Sepolia | 84532 | ✅ Доступно для тестирования | -## Additional Resources -- [Subscriptions Reference](/base-account/reference/base-pay/subscriptions-overview) -- [Spend Permissions](/base-account/improve-ux/spend-permissions) +## Дополнительные ресурсы +- [Справочник по подпискам](/base-account/reference/base-pay/subscriptions-overview) +- [Разрешения на траты](/base-account/improve-ux/spend-permissions) import PolicyBanner from "/snippets/PolicyBanner.mdx"; - \ No newline at end of file + diff --git a/docs/base-account/guides/authenticate-users.mdx b/docs/base-account/guides/authenticate-users.mdx index 346a5b99..4a857a08 100644 --- a/docs/base-account/guides/authenticate-users.mdx +++ b/docs/base-account/guides/authenticate-users.mdx @@ -1,27 +1,27 @@ --- -title: "Authenticate Users" -description: "Let a user click “Sign in with Base,” prove ownership of their onchain account, and give your server everything it needs to create a session – using open standards and no passwords" +title: "Аутентификация пользователей" +description: "Позвольте пользователю нажать «Sign in with Base», подтвердить владение его ончейн-аккаунтом и предоставить вашему серверу все необходимое для создания сессии – с использованием открытых стандартов и без паролей" --- import {BasePayButton} from "/snippets/BasePayButton.mdx" import {SignInWithBaseButton} from "/snippets/SignInWithBaseButton.mdx" -## Why wallet signatures instead of passwords? +## Почему подписи кошелька вместо паролей? -1. **No new passwords** – authentication happens with the key the user already controls. -2. **Nothing to steal or reuse** – each login is a one-off, domain-bound signature that never leaves the user’s device. -3. **Wallet-agnostic** – works in any EIP-1193 wallet (browser extension, mobile deep-link, embedded provider) and follows the open ["Sign in with Ethereum" (SIWE) EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) standard. +1. **Нет новых паролей** – аутентификация происходит с помощью ключа, которым пользователь уже управляет. +2. **Нечего украсть или повторно использовать** – каждый вход представляет собой одноразовую, привязанную к домену подпись, которая никогда не покидает устройство пользователя. +3. **Не зависит от кошелька** – работает с любым EIP-1193 кошельком (браузерное расширение, мобильная deep-link, встроенный провайдер) и следует открытому стандарту ["Sign in with Ethereum" (SIWE) EIP-4361](https://eips.ethereum.org/EIPS/eip-4361). -Base Accounts build on those standards so you can reuse any SIWE tooling – while still benefiting from passkeys, session keys, and smart-wallet security. +Base Accounts построены на этих стандартах, поэтому вы можете повторно использовать любой инструментарий SIWE – и при этом пользоваться преимуществами passkeys, сессионных ключей и безопасности смарт-кошельков. -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте руководству по бренду** -If you intend on using the `SignInWithBaseButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать `SignInWithBaseButton`, пожалуйста, следуйте [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. -## High-level flow +## Общая схема процесса ```mermaid sequenceDiagram @@ -31,33 +31,33 @@ sequenceDiagram participant SDK participant Account - alt Generate locally + alt Генерация локально Browser->>Browser: randomNonce() - else Prefetch - Browser->>AppServer: GET /auth/nonce (on page load) + else Предварительная загрузка + Browser->>AppServer: GET /auth/nonce (при загрузке страницы) AppServer-->>Browser: nonce end - User->>Browser: Click "Sign in with Base" + User->>Browser: Нажимает "Sign in with Base" Browser->>SDK: wallet_connect(signInWithEthereum {nonce}) SDK->>Account: wallet_connect(...) - User->>Account: Approve connection + User->>Account: Подтверждает соединение Account-->>SDK: {address, message, signature} SDK-->>Browser: {address, message, signature} Browser-->>AppServer: POST /auth/verify {address, message, signature} - AppServer-->>Browser: session token / JWT + AppServer-->>Browser: токен сессии / JWT ``` -**Undeployed Smart Wallets?**
Base Account signatures include the ERC-6492 wrapper so they can be verified even before the wallet contract is deployed. Viem’s `verifyMessage` and `verifyTypedData` handle this automatically. +**Не развернутые смарт-кошельки?**
Подписи Base Account включают обертку ERC-6492 поэтому их можно верифицировать даже до развертывания контракта кошелька. Функции `verifyMessage` и `verifyTypedData` в Viem обрабатывают это автоматически.
-## Implementation +## Реализация -### Install Dependencies +### Установите зависимости -Make sure to install the dependencies: +Убедитесь, что установили зависимости: ```bash @@ -78,22 +78,22 @@ bun add @base-org/account @base-org/account-ui -### Code Snippets +### Примеры кода ```ts Browser (SDK) import { createBaseAccountSDK } from "@base-org/account"; import crypto from 'crypto'; -// Initialize the SDK +// Инициализируем SDK const provider = createBaseAccountSDK({appName: 'My App'}).getProvider(); -// 1 — get a fresh nonce (generate locally or prefetch from backend) +// 1 — получаем свежий nonce (генерируем локально или предварительно загружаем с бэкенда) const nonce = window.crypto.randomUUID().replace(/-/g, ''); -// OR prefetch from server +// ИЛИ предзагружаем с сервера // const nonce = await fetch('/auth/nonce').then(r => r.text()); -// 2 — switch to Base Chain +// 2 — переключаемся на сеть Base const switchChainResponse = await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: '0x2105' }], @@ -101,7 +101,7 @@ const switchChainResponse = await provider.request({ console.log('Switch chain response:', switchChainResponse); -// 3 — connect and authenticate +// 3 — подключаемся и аутентифицируемся try { const { accounts } = await provider.request({ method: 'wallet_connect', @@ -136,27 +136,27 @@ export async function verifySig(req, res) { const { address, message, signature } = req.body; const valid = await client.verifyMessage({ address, message, signature }); if (!valid) return res.status(401).json({ error: 'Invalid signature' }); - // create session / JWT + // создаем сессию / JWT res.json({ ok: true }); } ``` -If using the above code beyond Base Account, note that not every wallet supports the new [wallet_connect method](/base-account/reference/core/provider-rpc-methods/wallet_connect) yet. If the call throws [method_not_supported], fall back to using eth_requestAccounts and personal_sign. +Если используете код выше за пределами Base Account, обратите внимание, что не все кошельки еще поддерживают новый метод [wallet_connect method](/base-account/reference/core/provider-rpc-methods/wallet_connect). Если вызов выбрасывает ошибку [method_not_supported], вернитесь к использованию eth_requestAccounts и personal_sign. -To avoid [popup blockers](/base-account/more/troubleshooting/usage-details/popups#default-blocking-behavior), fetch or generate the nonce before the user presses "Sign in with Base" (for example on page load). For security, the only requirement is that your backend keeps track of every nonce and refuses any that are reused – regardless of where it originated. +Чтобы избежать [блокировки всплывающих окон](/base-account/more/troubleshooting/usage-details/popups#default-blocking-behavior), получайте или генерируйте nonce до того, как пользователь нажмет "Sign in with Base" (например, при загрузке страницы). Для безопасности требуется только, чтобы ваш бэкенд отслеживал каждый nonce и отклонял те, которые используются повторно – независимо от их происхождения. {/* TODO: Link Wagmi Sign in with Base guide -For a full React example see the React + Wagmi guide. +Полный пример на React смотрите в руководстве по React + Wagmi. */} -### Example Express Server +### Пример сервера на Express ```ts title="server/auth.ts" import crypto from 'crypto'; @@ -167,7 +167,7 @@ import { base } from 'viem/chains'; const app = express(); app.use(express.json()); -// Simple in-memory nonce store (swap for Redis or DB in production) +// Простое хранилище nonce в памяти (замените на Redis или БД в продакшене) const nonces = new Set(); app.get('/auth/nonce', (_, res) => { @@ -181,26 +181,26 @@ const client = createPublicClient({ chain: base, transport: http() }); app.post('/auth/verify', async (req, res) => { const { address, message, signature } = req.body; - // 1. Check nonce hasn\'t been reused + // 1. Проверяем, что nonce не использовался повторно const nonce = message.match(/at (\w{32})$/)?.[1]; if (!nonce || !nonces.delete(nonce)) { return res.status(400).json({ error: 'Invalid or reused nonce' }); } - // 2. Verify signature + // 2. Проверяем подпись const valid = await client.verifyMessage({ address, message, signature }); if (!valid) return res.status(401).json({ error: 'Invalid signature' }); - // 3. Create session / JWT here + // 3. Создаем сессию / JWT здесь res.json({ ok: true }); }); app.listen(3001, () => console.log('Auth server listening on :3001')); ``` -## Add the Base Sign In With Base Button +## Добавьте кнопку "Sign in with Base" -Use the pre-built component for a native look-and-feel: +Используйте готовый компонент для нативного внешнего вида и поведения: ```tsx title="App.tsx" import { SignInWithBaseButton } from '@base-org/account-ui/react'; @@ -215,11 +215,11 @@ export function App() { } ``` -See full props and theming options in the [Button Reference](/base-account/reference/ui-elements/sign-in-with-base-button) and [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines). +Полный список пропсов и параметров темизации смотрите в [Button Reference](/base-account/reference/ui-elements/sign-in-with-base-button) и [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines). -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте Brand Guidelines** -If you intend on using the `SignInWithBaseButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать `SignInWithBaseButton`, пожалуйста, следуйте [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. diff --git a/docs/base-account/guides/migration-guide.mdx b/docs/base-account/guides/migration-guide.mdx index af94aa53..474367f5 100644 --- a/docs/base-account/guides/migration-guide.mdx +++ b/docs/base-account/guides/migration-guide.mdx @@ -1,52 +1,52 @@ --- -title: "Migrate from Coinbase Wallet SDK" -description: "A guide to migrating from the Coinbase Wallet SDK to the Base Account SDK" +title: "Переход с Coinbase Wallet SDK" +description: "Руководство по переходу с Coinbase Wallet SDK на Base Account SDK" --- -## Overview +## Обзор -The Base Account SDK allows Base Account users to connect 3rd party mobile and web applications. The Base Account SDK is the successor to the Coinbase Wallet SDK, which is now considered legacy. +Base Account SDK позволяет пользователям Base Account подключать сторонние мобильные и веб-приложения. Base Account SDK является преемником Coinbase Wallet SDK, который теперь считается устаревшим. -Developers should integrate the Base Account SDK such that users connect to use it via a "Sign in with Base" or "Base" button. +Разработчикам следует интегрировать Base Account SDK таким образом, чтобы пользователи подключались через кнопку "Sign in with Base" или "Base". -We do not recommend immediately replacing existing "Coinbase Wallet" buttons in your app, but rather add the Base Account button as an additional option, next to a "Coinbase Wallet" button. This will allow a transition period for users to get familiar with the new Base brand. +Мы не рекомендуем немедленно заменять существующие кнопки "Coinbase Wallet" в вашем приложении. Вместо этого лучше добавить кнопку Base Account как дополнительную опцию рядом с кнопкой "Coinbase Wallet". Это позволит обеспечить переходный период, в течение которого пользователи смогут ознакомиться с новым брендом Base. -Driving this change is a transition of our mobile app: the Coinbase Wallet app is now the Base app. We are gradually transitioning all of our users to have Base Accounts, which are powered by our Smart Wallet platform. +Эти изменения связаны с переходом нашего мобильного приложения: приложение Coinbase Wallet теперь стало приложением Base. Мы постепенно переводим всех наших пользователей на Base Accounts, которые работают на нашей платформе смарт-кошельков. -Below is a table of existing users and how they will connect to apps now and in the future: +Ниже приведена таблица, показывающая, как существующие пользователи подключаются к приложениям сейчас и как будут подключаться в будущем: -| User Type | Today | Future (~Fall 2025) | -|-----------|-------|---------------------| -| Smart Wallet users (web and mobile app) | Automatically have a Base Account, can use "Sign in with Base" | No change | -| New Base app users | Automatically have a Base Account, can use "Sign in with Base" | No change | -| Coinbase Wallet Extension Users | Should continue to connect with "Coinbase Wallet" button | Will have a path to migrate to Base Account and use "Sign in with Base" | -| Coinbase Wallet mobile app EOA users | Should continue to connect with "Coinbase Wallet" button | Will have a path to migrate to Base Account and use "Sign in with Base" | +| Тип пользователя | Сейчас | Будущее (~Осень 2025) | +|------------------|--------|-----------------------| +| Пользователи смарт-кошельков (веб и мобильное приложение) | Автоматически имеют Base Account, могут использовать "Sign in with Base" | Без изменений | +| Новые пользователи приложения Base | Автоматически имеют Base Account, могут использовать "Sign in with Base" | Без изменений | +| Пользователи расширения Coinbase Wallet | Продолжают подключаться через кнопку "Coinbase Wallet" | Получат возможность перейти на Base Account и использовать "Sign in with Base" | +| Пользователи мобильного приложения Coinbase Wallet с EOA-кошельками | Продолжают подключаться через кнопку "Coinbase Wallet" | Получат возможность перейти на Base Account и использовать "Sign in with Base" | -## Changes to user experience when click "Coinbase Wallet" +## Изменения в пользовательском опыте при нажатии на "Coinbase Wallet" -As of SDK v4.0, users without Coinbase Wallet extension are directed to a popup window where they can choose to connect with the mobile app, via WalletLink, or use a passkey-powered Smart Wallet natively on the web. +Начиная с SDK v4.0, пользователи без расширения Coinbase Wallet перенаправляются во всплывающее окно, где они могут выбрать подключение через мобильное приложение (через WalletLink) или использовать смарт-кошелек на основе пасскей непосредственно в вебе. -This will continue to be the case, but the logged out experience has changed to educate Smart Wallet users that they should be using "Sign in with Base" in the future. Here is how it looks on desktop. +Этот механизм сохранится, но опыт для неавторизованных пользователей изменился: теперь он информирует пользователей смарт-кошельков о том, что в будущем им следует использовать "Sign in with Base". Вот как это выглядит на десктопе.
Create Wallet Flow
- Desktop experience showing the updated logged out flow for Coinbase Wallet users + Опыт работы на десктопе, показывающий обновленный процесс для неавторизованных пользователей Coinbase Wallet
-If you would like to avoid users seeing any popup window, we recommend using a version of the Coinbase Wallet SDK < 4.0. +Если вы хотите, чтобы пользователи вообще не видели всплывающих окон, мы рекомендуем использовать версию Coinbase Wallet SDK < 4.0. -You can find the latest version of the Coinbase Wallet SDK [here](https://github.com/coinbase/coinbase-wallet-sdk/releases). +Вы можете найти последнюю версию Coinbase Wallet SDK [здесь](https://github.com/coinbase/coinbase-wallet-sdk/releases). -## How to migrate? +## Как выполнить переход? -If you're using the SDK, you can simply replace the Coinbase Wallet SDK with the Base Account SDK. +Если вы используете SDK напрямую, вы можете просто заменить Coinbase Wallet SDK на Base Account SDK. ```tsx import { createBaseAccountSDK } from "@base-org/account"; @@ -56,10 +56,10 @@ const baseAccount = createBaseAccountSDK({ }); ``` -For more information please refer to the [Quickstart](/base-account/quickstart/web) guide. +Для получения дополнительной информации обратитесь к руководству [Быстрый старт](/base-account/quickstart/web). -If you're using a third party library, you can follow the [Wagmi](/base-account/framework-integrations/wagmi/setup), [Dynamic](/base-account/framework-integrations/nextjs-with-dynamic) or [Privy](/base-account/framework-integrations/privy/setup) guides. +Если вы используете стороннюю библиотеку, вы можете следовать руководствам по интеграции с [Wagmi](/base-account/framework-integrations/wagmi/setup), [Dynamic](/base-account/framework-integrations/nextjs-with-dynamic) или [Privy](/base-account/framework-integrations/privy/setup). -We will have a more complete migration guide in the near future. +В ближайшем будущем мы представим более полное руководство по миграции. diff --git a/docs/base-account/guides/sign-and-verify-typed-data.mdx b/docs/base-account/guides/sign-and-verify-typed-data.mdx index 180fb15e..cd6cf49f 100644 --- a/docs/base-account/guides/sign-and-verify-typed-data.mdx +++ b/docs/base-account/guides/sign-and-verify-typed-data.mdx @@ -1,35 +1,35 @@ --- -title: "Sign and Verify Typed Data" -description: "EIP-712 structured data signing and verification for Base Account" +title: "Подпись и проверка типизированных данных" +description: "Подпись и проверка структурированных данных EIP-712 для Base Account" --- -## Overview +## Обзор -Base Account uses [Smart Wallet contracts](https://github.com/coinbase/smart-wallet) under the hood. Smart contract wallets introduce a few differences in how messages are signed compared to traditional Externally Owned Accounts (EOAs). This guide explains how to properly implement message signing using Base Account, covering both standard messages and typed data signatures, as well as some edge cases. +Base Account использует [контракты смарт-кошельков](https://github.com/coinbase/smart-wallet). Смарт-контрактные кошельки имеют некоторые отличия в том, как подписываются сообщения, по сравнению с традиционными аккаунтами, контролируемыми извне (Externally Owned Accounts, EOA). В этом руководстве объясняется, как правильно реализовать подпись сообщений с помощью Base Account, рассматривая как стандартные сообщения, так и подписи типизированных данных, а также некоторые частные случаи. -## Introduction +## Введение -Before walking through the details of how to sign and verify messages using Base Account, it's important to understand some of the use cases of signing messages with wallets, as well as the key differences between EOAs and smart contracts when it comes to signing messages. +Прежде чем углубляться в детали того, как подписывать и проверять сообщения с помощью Base Account, важно понять некоторые сценарии использования подписей кошелька, а также ключевые различия между EOA и смарт-контрактами в части подписи сообщений. -### Use Cases for Wallet Signatures +### Сценарии использования подписей кошелька -Blockchain-based apps use wallet signatures for two main categories: +Приложения на основе блокчейна используют подписи кошелька для двух основных целей: -1. **Signatures for offchain verification**: Used for authenticating users in onchain apps (e.g., Sign-In with Ethereum) to avoid spoofing. The signature is not used for any onchain action. +1. **Подписи для оффчейн-верификации**: Используются для аутентификации пользователей в ончейн-приложениях (например, Sign-In with Ethereum), чтобы предотвратить спуфинг (подмену). Подпись не используется для каких-либо действий в блокчейне. -2. **Signatures for onchain verification**: Used for signing onchain permissions (e.g., [Permit2](https://github.com/Uniswap/permit2)) or batching transactions. The signature is usually stored for future transactions. +2. **Подписи для ончейн-верификации**:Используются для подписи разрешений в блокчейне (например, [Permit2](https://github.com/Uniswap/permit2)) или пакетной обработки транзакций. Подпись обычно хранится для будущих транзакций. -### Smart Contract Wallet Differences +### Отличия смарт-контрактных кошельков -Smart contract wallets handle signatures differently from EOAs in several ways: +Смарт-контрактные кошельки обрабатывают подписи иначе, чем EOA, несколькими способами: -- The contract itself doesn't produce signatures - instead, the owner (e.g., passkey) signs messages -- Verification happens through the `isValidSignature` function defined in [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) -- Smart contract wallet addresses are often deterministic, allowing signature support before deployment via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) +- Сам контракт не создает подписи - вместо этого сообщения подписывает владелец (например, passkey). +- Проверка происходит через функцию `isValidSignature`, определенную в [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) +- Адреса смарт-контрактных кошельков часто детерминированы, что позволяет поддерживать подписи еще до развертывания кошелька через [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) -## High-level flow +## Общая схема процесса -In this guide, we'll walk through the high-level flow of signing and verifying messages using Base Account. +В этом руководстве мы рассмотрим общую схему подписи и проверки сообщений с помощью Base Account. ```mermaid sequenceDiagram @@ -39,35 +39,35 @@ sequenceDiagram participant SDK participant Account - User->>Browser: Trigger signing action + User->>Browser: Инициирует действие подписи Browser->>AppServer: GET /typed-data/prepare - AppServer-->>Browser: EIP-712 payload + AppServer-->>Browser: Полезная нагрузка EIP-712 Browser->>SDK: eth_signTypedData_v4 SDK->>Account: eth_signTypedData_v4(payload) - User->>Account: Review and approve signature - Account-->>SDK: signature - SDK-->>Browser: signature + User->>Account: Проверяет и подтверждает подпись + Account-->>SDK: подпись + SDK-->>Browser: подпись Browser-->>AppServer: POST /typed-data/verify {payload, signature} - AppServer-->>Browser: verification result + AppServer-->>Browser: результат проверки ``` -## Implementation +## Реализация -For the purposes of this guide, we'll use a simple example of a typed data payload that contains a permission -to spend user's funds (see [Spend Permissions](/base-account/improve-ux/spend-permissions)) +Для целей этого руководства мы используем простой пример полезной нагрузки типизированных данных, +содержащей разрешение на трату средств пользователя (см. [Spend Permissions](/base-account/improve-ux/spend-permissions)) -### Code Snippets +### Примеры кода ```ts Browser (SDK) import { createBaseAccountSDK } from "@base-org/account"; -// Initialize the SDK +// Инициализируем SDK const provider = createBaseAccountSDK().getProvider(); -// 1 — Prepare the typed data payload +// 1 — Подготавливаем полезную нагрузку типизированных данных const typedData = { domain: { name: 'Spend Permission Manager', @@ -92,7 +92,7 @@ const typedData = { message: spendPermissionData, }; -// 2 — Request signature from user +// 2 — Запрашиваем подпись у пользователя try { const accounts = await provider.request({ method: 'eth_requestAccounts' @@ -103,7 +103,7 @@ try { params: [accounts[0], JSON.stringify(typedData)] }); - // 3 — Send to backend for verification + // 3 — Отправляем на бэкенд для проверки const response = await fetch('/typed-data/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -134,7 +134,7 @@ export async function verifyTypedData(req, res) { const { typedData, signature, address } = req.body; try { - // Verify the typed data signature + // Проверяем подпись типизированных данных const valid = await client.verifyTypedData({ address, domain: typedData.domain, @@ -148,14 +148,14 @@ export async function verifyTypedData(req, res) { return res.status(401).json({ error: 'Invalid signature' }); } - // Additional validation logic here + // Дополнительная логика проверки здесь // e.g., check expiry, nonce, permissions, etc. const now = Math.floor(Date.now() / 1000); if (typedData.message.expiry < now) { return res.status(401).json({ error: 'Signature expired' }); } - // Process the verified typed data + // Обрабатываем проверенные типизированные данные res.json({ valid: true, message: 'Signature verified successfully', @@ -169,7 +169,7 @@ export async function verifyTypedData(req, res) { ``` -## Example Express Server +## Пример сервера на Express ```ts title="server/typed-data.ts" import express from 'express'; @@ -184,17 +184,17 @@ const client = createPublicClient({ transport: http() }); -// Simple nonce store (use Redis/DB in production) +// Простое хранилище nonce (используйте Redis/БД в продакшене) const usedNonces = new Set(); app.get('/typed-data/prepare', (req, res) => { const { userAddress, action, resource } = req.query; const nonce = Math.floor(Math.random() * 1000000); - const expiry = Math.floor(Date.now() / 1000) + 3600; // 1 hour + const expiry = Math.floor(Date.now() / 1000) + 3600; // 1 час const typedData = { - // YOUR TYPED DATA HERE + // ВАШИ ТИПИЗИРОВАННЫЕ ДАННЫЕ ЗДЕСЬ } res.json(typedData); @@ -204,19 +204,19 @@ app.post('/typed-data/verify', async (req, res) => { const { typedData, signature, address } = req.body; try { - // 1. Check nonce hasn't been reused + // 1. Проверяем, что nonce не использовался повторно const nonceKey = `${address}-${typedData.message.nonce}`; if (usedNonces.has(nonceKey)) { return res.status(400).json({ error: 'Nonce already used' }); } - // 2. Check expiry + // 2. Проверяем срок действия const now = Math.floor(Date.now() / 1000); if (typedData.message.expiry < now) { return res.status(400).json({ error: 'Signature expired' }); } - // 3. Verify signature + // 3. Проверяем подпись const valid = await client.verifyTypedData({ address, domain: typedData.domain, @@ -230,10 +230,10 @@ app.post('/typed-data/verify', async (req, res) => { return res.status(401).json({ error: 'Invalid signature' }); } - // 4. Mark nonce as used + // 4. Помечаем nonce как использованный usedNonces.add(nonceKey); - // 5. Process the verified action + // 5. Обрабатываем проверенное действие res.json({ valid: true, message: 'Typed data verified successfully', @@ -249,34 +249,34 @@ app.post('/typed-data/verify', async (req, res) => { app.listen(3001, () => console.log('Typed data server listening on :3001')); ``` -## Best Practices +## Рекомендуемые практики -### Domain Separation -Always use unique domain parameters to prevent signature replay across different applications: +### Разделение доменов +Всегда используйте уникальные параметры домена, чтобы предотвратить повторное использование подписи в разных приложениях: ```tsx const domain = { - name: 'Your App Name', // Unique app identifier - version: '1', // Version your types - chainId: 8453, // Network-specific - verifyingContract: contractAddr // Contract that will verify + name: 'Your App Name', // Уникальный идентификатор приложения + version: '1', // Версионируйте ваши типы данных + chainId: 8453, // Определено для конкретной сети + verifyingContract: contractAddr // Контракт, который будет выполнять проверку }; ``` -### Nonce Management -Include nonces to prevent replay attacks: +### Управление nonce +Включайте nonce, чтобы предотвратить атаки повторного использования: ```tsx -// Generate unique nonces +// Генерируем уникальные nonce const nonce = crypto.randomBytes(16).toString('hex'); -// Store and validate nonces server-side +// Храните и проверяйте nonce на стороне сервера const usedNonces = new Set(); // Use Redis/DB in production ``` -### Expiry Times -Always include expiry timestamps for time-bound signatures: +### Сроки действия +Всегда включайте метки времени истечения срока действия для ограниченных по времени подписей: ```tsx -const expiry = Math.floor(Date.now() / 1000) + 3600; // 1 hour +const expiry = Math.floor(Date.now() / 1000) + 3600; // 1 час ``` diff --git a/docs/base-account/guides/tips/inspect-txn-simulation.mdx b/docs/base-account/guides/tips/inspect-txn-simulation.mdx index 0c5b4829..645cc8b2 100644 --- a/docs/base-account/guides/tips/inspect-txn-simulation.mdx +++ b/docs/base-account/guides/tips/inspect-txn-simulation.mdx @@ -1,11 +1,11 @@ --- -title: "Transaction Simulation Data" +title: "Данные симуляции транзакции" --- -There is a hidden feature which enables you to easily copy transaction simulation request and response data which can then be pasted it in a text editor to inspect. +Существует скрытая функция, которая позволяет легко копировать данные запроса и ответа для симуляции транзакции, а затем вставлять их в текстовый редактор для изучения. -## Instructions -- Click the area defined in red **_five times_**, then paste the copied data in a text editor. +## Инструкция +- Кликните в область, обозначенную красным, **_пять раз_**, а затем вставьте скопированные данные в текстовый редактор.
diff --git a/docs/base-account/guides/tips/popup-tips.mdx b/docs/base-account/guides/tips/popup-tips.mdx index 576aa36c..5364e78d 100644 --- a/docs/base-account/guides/tips/popup-tips.mdx +++ b/docs/base-account/guides/tips/popup-tips.mdx @@ -3,36 +3,35 @@ title: "Popup Tips" --- -## Overview -When a Base Account is connected and Coinbase Wallet SDK receives a request, it opens -[keys.coinbase.com](https://keys.coinbase.com/) in a popup window and passes the request to the popup for handling. -Keep the following points in mind when working with the Base Account popup. +## Обзор +Когда подключен Base Account (смарт-аккаунт) и Coinbase Wallet SDK получает запрос, он открывает сайт +[keys.coinbase.com](https://keys.coinbase.com/) во всплывающем окне (popup) и передает запрос в это окно для обработки. +При работе со всплывающим окном Base Account учитывайте следующие моменты. -## Default blocking behavior -- Most modern browsers block all popups by default, unless they are triggered by a click. -- If a popup is blocked the browser shows a notification to the user, allowing them to manage popup settings. +## Поведение блокировки по умолчанию +- Большинство современных браузеров по умолчанию блокируют все всплывающие окна, если они не вызваны кликом пользователя. +- Если окно заблокировано, браузер показывает пользователю уведомление, позволяя управлять настройками всплывающих окон. + +### Что с этим делать +- Убедитесь, что между кликом по кнопке и запросом на открытие окна Base Account нет дополнительной логики, так как браузеры могут воспринимать такой запрос как программно инициированный. +- Если логика неизбежна, сведите ее к минимуму и тщательно тестируйте во всех поддерживаемых браузерах. -### What to do about it -- Ensure there is no additional logic between the button click and the request to open the Base Account popup, -as browsers might perceive the request as programmatically initiated. -- If logic is unavoidable, keep it minimal and test thoroughly in all supported browsers. ## `Cross-Origin-Opener-Policy` -If the Base Account popup opens and displays an error or infinite spinner, it may be due to the dapp's `Cross-Origin-Opener-Policy`. Be sure to use a directive that allows the Base Account popup to function. +Если окно Base Account открывается и показывает ошибку или бесконечный спиннер, это может быть связано с заголовком `Cross-Origin-Opener-Policy` вашего dapp. Убедитесь, что используется директива, которая позволяет окну Base Account функционировать. -- ✅ Allows Base Account popup to function - - `unsafe-none` (default) - - `same-origin-allow-popups` (recommended) -- ❌ Breaks Base Account popup +- ✅ Позволяет работать окну Base Account + - `unsafe-none` (по умолчанию) + - `same-origin-allow-popups` (рекомендуется) +- ❌ Ломает работу окна Base Account - `same-origin` -For more detailed information refer to the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy). +Для получения более подробной информации обратитесь к [документации MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy). -## Base Account popup 'linger' behavior -- Sometimes a dapp may programmatically make a followup request based on the response to a previous request. -Normally, browsers block these programmatic requests to open popups. -- To address this, after the Base Account popup responds to a request, it will linger for 200ms to listen for another incoming request before closing. - - If a request is received *during* this 200ms window, it will be received and handled within the same popup window. - - If a request is received *after* the 200ms window and the popup has closed, opening the Base Account popup will be blocked by the browser. - \ No newline at end of file +## Поведение окна Base Account: "задержка" перед закрытием +- Иногда dapp может программно отправлять последующий запрос на основе ответа на предыдущий запрос. Обычно браузеры блокируют такие программные запросы на открытие всплывающих окон. +- Чтобы решить эту проблему, после того как окно Base Account ответит на запрос, оно будет оставаться открытым в течение 200 мс, "прислушиваясь" к возможному следующему входящему запросу, прежде чем закрыться. + - Если запрос получен в течение этого 200-миллисекундного интервала, он будет принят и обработан в том же самом всплывающем окне. + - Если запрос получен после истечения 200 мс и окно уже закрылось, попытка открыть окно Base Account будет заблокирована браузером. + diff --git a/docs/base-account/improve-ux/batch-transactions.mdx b/docs/base-account/improve-ux/batch-transactions.mdx index 88e1fe7c..f204b64e 100644 --- a/docs/base-account/improve-ux/batch-transactions.mdx +++ b/docs/base-account/improve-ux/batch-transactions.mdx @@ -1,14 +1,14 @@ --- -title: "Batch Transactions" +title: "Пакетные транзакции" --- -With Base Account, you can send multiple onchain calls in a single transaction. Doing so improves the UX of multi-step interactions by reducing them to a single click. A common example of where you might want to leverage batch transactions is an ERC-20 `approve` followed by a swap. +С помощью Base Account вы можете отправлять несколько ончейн-вызовов в одной транзакции. Это улучшает пользовательский опыт (UX) многошаговых операций, сводя их к одному клику. Типичный пример, где можно использовать пакетные транзакции - это вызов `approve` для токена ERC-20, за которым следует обмен (swap). -You can submit batch transactions by using the `wallet_sendCalls` RPC method, defined in [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792). +Вы можете отправлять пакетные транзакции, используя RPC-метод `wallet_sendCalls`, определенный в [EIP-5792](https://eips.ethereum.org/EIPS/eip-5792). -## Installation +## Установка -Install the Base Account SDK: +Установите SDK Base Account: ```bash npm @@ -28,11 +28,11 @@ bun add @base-org/account ``` -## Setup +## Настройка -### Initialize the SDK +### Инициализация SDK -Import and create the Base Account SDK instance: +Импортируйте и создайте экземпляр SDK Base Account: ```tsx import { createBaseAccountSDK, base } from '@base-org/account'; @@ -46,11 +46,11 @@ const sdk = createBaseAccountSDK({ const provider = sdk.getProvider(); ``` -## Basic Batch Transaction +## Базовая пакетная транзакция -### Simple Multiple Transfers +### Простые множественные переводы -Send multiple ETH transfers in a single transaction: +Отправьте несколько переводов ETH в одной транзакции: ```tsx import { createBaseAccountSDK, getCryptoKeyAccount, base } from '@base-org/account'; @@ -66,32 +66,32 @@ const provider = sdk.getProvider(); async function sendBatchTransfers() { try { - // Get crypto account + // Получаем криптоаккаунт const cryptoAccount = await getCryptoKeyAccount(); const fromAddress = cryptoAccount?.account?.address; - // Prepare batch calls + // Подготавливаем пакет вызовов const calls = [ { to: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', value: numberToHex(parseEther('0.001')), // 0.001 ETH - data: '0x', // Empty data for simple transfer + data: '0x', // Пустые данные для простого перевода }, { to: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E456', value: numberToHex(parseEther('0.001')), // 0.001 ETH - data: '0x', // Empty data for simple transfer + data: '0x', // Пустые данные для простого перевода } ]; - // Send batch transaction + // Отправляем пакетную транзакцию const result = await provider.request({ method: 'wallet_sendCalls', params: [{ version: '2.0.0', from: fromAddress, chainId: numberToHex(base.constants.CHAIN_IDS.base), - atomicRequired: true, // All calls must succeed or all fail + atomicRequired: true, // Все вызовы должны завершиться успешно, иначе все будут отменены calls: calls }] }); @@ -105,17 +105,17 @@ async function sendBatchTransfers() { } ``` -## Contract Interactions +## Взаимодействие с контрактами -### ERC-20 Approve and Transfer +### Approve и перевод токена ERC-20 -A common pattern is to approve and then transfer ERC-20 tokens: +Часто встречающийся паттерн - утвердить (approve), а затем перевести токены ERC-20: ```tsx import { createBaseAccountSDK, getCryptoKeyAccount, base } from '@base-org/account'; import { numberToHex, parseUnits, encodeFunctionData } from 'viem'; -// ERC-20 ABI for approve and transfer functions +// ABI ERC-20 для функций approve и transfer const erc20Abi = [ { name: 'approve', @@ -150,8 +150,8 @@ async function approveAndTransfer() { const cryptoAccount = await getCryptoKeyAccount(); const fromAddress = cryptoAccount?.account?.address; - const tokenAddress = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // USDC on Base - const spenderAddress = '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad'; // Example spender + const tokenAddress = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // USDC на Base + const spenderAddress = '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad'; // Пример получателя разрешения const recipientAddress = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045'; const amount = parseUnits('10', 6); // 10 USDC (6 decimals) @@ -191,11 +191,11 @@ async function approveAndTransfer() { } ``` -## Advanced Features +## Расширенные возможности -### Checking Wallet Capabilities +### Проверка возможностей кошелька -Before sending batch transactions, you can check if the wallet supports atomic batching: +Перед отправкой пакетных транзакций вы можете проверить, поддерживает ли кошелек атомарное объединение (atomic batching): ```tsx async function checkCapabilities() { @@ -226,9 +226,9 @@ async function checkCapabilities() { } ``` -### Non-Atomic Batching +### Неатомарное объединение -Sometimes you want calls to execute sequentially, even if some fail: +Иногда требуется, чтобы вызовы выполнялись последовательно, даже если некоторые из них завершатся неудачей: ```tsx const result = await provider.request({ @@ -237,15 +237,15 @@ const result = await provider.request({ version: '2.0.0', from: fromAddress, chainId: numberToHex(base.constants.CHAIN_IDS.base), - atomicRequired: false, // Allow partial execution + atomicRequired: false, // Разрешить частичное выполнение calls: calls }] }); ``` -## Error Handling +## Обработка ошибок -Handle common batch transaction errors: +Обработка типичных ошибок пакетных транзакций: ```tsx async function sendBatchWithErrorHandling(calls: any[]) { diff --git a/docs/base-account/improve-ux/magic-spend.mdx b/docs/base-account/improve-ux/magic-spend.mdx index 7607ebe0..1ef66b86 100644 --- a/docs/base-account/improve-ux/magic-spend.mdx +++ b/docs/base-account/improve-ux/magic-spend.mdx @@ -1,22 +1,22 @@ --- -title: "Use Coinbase Balances Onchain" -description: "How to use Coinbase balances onchain with Base Account" +title: "Использование балансов Coinbase в ончейн-среде" +description: "Как использовать балансы Coinbase в ончейн-среде с помощью Base Account" --- -With MagicSpend, Base Account users can use their Coinbase balances onchain. This means users can easily start using onchain apps without needing to onramp funds into their wallet. +Благодаря функции MagicSpend пользователи Base Account могут использовать свои балансы Coinbase в ончейн-операциях. Это означает, что пользователи могут легко начать использовать ончейн-приложения без необходимости пополнять баланс (onramp) в своем кошельке. -This also means that apps might not have all the balance information typically available to them by reading onchain data. Base Account indicates that this is the case by responding to [`wallet_getCapabilities` RPC calls](https://eip5792.xyz/reference/getCapabilities) with the `auxiliaryFunds` capability for each chain Base Account users can use their Coinbase balances on. +Это также означает, что приложениям может быть недоступна вся информация о балансе, которая обычно получается путем чтения ончейн-данных. Base Account указывает на это, отвечая на [RPC-запросы `wallet_getCapabilities`](https://eip5792.xyz/reference/getCapabilities) возможностью (capability) `auxiliaryFunds` для каждой цепи, на которой пользователи Base Account могут использовать свои балансы Coinbase. -If your app supports Base Account, it should not assume it knows the full balances available to a user if the `auxiliaryFunds` capability is present on a given chain. For example, if your app disables a transaction button if it sees that the wallet has insufficient funds, your app should take `auxiliaryFunds` into account and enable the button if the account has `auxiliaryFunds` on the chain the user is transacting on. +Если ваше приложение поддерживает Base Account, оно не должно предполагать, что знает все доступные пользователю балансы, если для данной цепи присутствует возможность `auxiliaryFunds`. Например, если ваше приложение отключает кнопку транзакции, когда видит, что в кошельке недостаточно средств, оно должно учитывать `auxiliaryFunds` и активировать кнопку, если у аккаунта есть `auxiliaryFunds` в цепи, где пользователь совершает транзакцию. -## Why it matters +## Почему это важно -MagicSpend makes onboarding smoother by letting users pay gas or send funds even when their onchain wallet balance is **zero**. Your interface should therefore _never_ disable an action just because the onchain balance is insufficient. +MagicSpend упрощает вовлечение пользователей, позволяя им оплачивать комиссии или отправлять средства, даже когда баланс их ончейн-кошелька равен **нулю**. Следовательно, ваш интерфейс _никогда_ не должен отключать действие только из-за недостаточного ончейн-баланса. -1. Ensure you have the user’s `address` stored in your component state (from your wallet connection flow). +1. Убедитесь, что `address` пользователя сохранен в состоянии вашего компонента (из вашего потока подключения кошелька). -2. Drop the component below into your UI. It will check whether MagicSpend (`auxiliaryFunds`) is available for that address on Base and if not, disable the send button accordingly. +2. Добавьте приведенный ниже компонент в ваш интерфейс. Он проверит, доступна ли MagicSpend (`auxiliaryFunds`) для данного адреса на Base, и в противном случае соответствующим образом отключит кнопку отправки. ```tsx title="SendButton.tsx" import { useEffect, useState } from "react"; @@ -31,14 +31,14 @@ const sdk = createBaseAccountSDK({ const provider = sdk.getProvider(); interface Props { - address?: string; // wallet address from your app state + address?: string; // адрес кошелька из состояния вашего приложения } export function SendButton({ address }: Props) { const [hasAuxFunds, setHasAuxFunds] = useState(null); useEffect(() => { - if (!address) return; // Wallet not connected yet + if (!address) return; // Кошелек еще не подключен (async () => { try { @@ -67,24 +67,24 @@ export function SendButton({ address }: Props) { } ``` -### What the code does +### Что делает этот код -1. Receives the current `address` from your own wallet logic. -2. Calls `wallet_getCapabilities` whenever the address changes. -3. Reads `auxiliaryFunds.supported` for the Base chain (`8453`). -4. Enables the button when MagicSpend is available; otherwise shows “Insufficient Balance”. +1. Получает текущий `address` из вашей собственной логики работы с кошельком. +2. Вызывает `wallet_getCapabilities` при каждом изменении адреса. +3. Считывает `auxiliaryFunds.supported` для цепи Base (`8453`). +4. Активирует кнопку, когда MagicSpend доступен; в противном случае показывает "Недостаточно средств". -## Base Pay integrates Magic Spend by default +## Base Pay интегрирует Magic Spend по умолчанию -Thanks to [Magic Spend](/base-account/improve-ux/magic-spend), [Base Pay](/base-account/guides/accept-payments) allows users to pay with their USDC balance on Coinbase by default. +Благодаря [Magic Spend](/base-account/improve-ux/magic-spend), [Base Pay](/base-account/guides/accept-payments) позволяет пользователям по умолчанию оплачивать с помощью своего баланса USDC на Coinbase.
Pay with Coinbase on Base Account
--- -## Next steps +## Следующие шаги -- Handle loading/error states if you need fine-grained UX -- Combine this check with your existing onchain balance logic for fallback flows +- Обрабатывайте состояния загрузки/ошибок, если требуется детальный контроль над пользовательским опытом +- Объедините эту проверку с вашей существующей логикой проверки ончейн-баланса для резервных сценариев diff --git a/docs/base-account/improve-ux/spend-permissions.mdx b/docs/base-account/improve-ux/spend-permissions.mdx index 2cfe719c..d0785e4b 100644 --- a/docs/base-account/improve-ux/spend-permissions.mdx +++ b/docs/base-account/improve-ux/spend-permissions.mdx @@ -1,41 +1,41 @@ --- -title: "Use Spend Permissions" -description: "Learn how to use Spend Permissions to allow a trusted spender to spend user assets" +title: "Использование разрешений на расходование" +description: "Узнайте, как использовать Spend Permissions для предоставления доверенной стороне права расходовать активы пользователя" --- -## Overview +## Обзор -Spend Permissions let you designate a trusted `spender` that can move assets out of a user's Base Account on their behalf. +Разрешения на расходование (Spend Permissions) позволяют назначить доверенную сторону (`spender`), которая может перемещать активы из Base Account пользователя от его имени. -After the user signs the permission, the `spender` can initiate transfers within the limits you define — no additional prompts, pop-ups, or signatures needed from the user. This powers seamless experiences such as subscription renewals, algorithmic trading, and automated payouts. +После того как пользователь подписывает разрешение, `spender` может инициировать переводы в пределах установленных вами лимитов - без дополнительных запросов, всплывающих окон или подписей от пользователя. Это обеспечивает бесперебойную работу для таких сценариев, как продление подписок, алгоритмическая торговля и автоматические выплаты. -Read more about the Spend Permission Manager contract and supported chains on [GitHub](https://github.com/coinbase/spend-permissions). +Подробнее о контракте менеджера Spend Permissions и поддерживаемых цепях читайте на [GitHub](https://github.com/coinbase/spend-permissions). - Spend Permissions for Base App Mini Apps are coming soon and will be supported in a future update. + Поддержка Spend Permissions для мини-приложений Base App появится в ближайшем будущем и будет добавлена в одном из следующих обновлений. -If you're using Sub Accounts, learn how Base Account can automatically fund Sub Accounts and optionally skip approval prompts using [Auto Spend Permissions](/base-account/improve-ux/sub-accounts#auto-spend-permissions). +Если вы используете Суб-аккаунты (Sub Accounts), узнайте, как Base Account может автоматически пополнять их и, при желании, пропускать запросы на подтверждение, используя [Auto Spend Permissions](/base-account/improve-ux/sub-accounts#auto-spend-permissions). -## Usage +## Использование -### Request a Spend Permission +### Запрос разрешения на расходование -You create an EIP-712 payload that describes the permission and ask the user to sign it. Store the resulting signature along with the permission data so you can register the permission on-chain later. The SDK helper below handles construction and signing for you. +Вы создаете полезную нагрузку (payload) EIP-712, описывающую разрешение, и просите пользователя подписать её. Сохраните полученную подпись вместе с данными разрешения, чтобы позднее зарегистрировать его в блокчейне. Помощник SDK ниже позаботится о формировании и подписании за вас. -| Field Name | Type | Description | -| ----------- | --------- | ---------------------------------------------------------------------------------------- | -| `account` | `address` | Smart account this spend permission is valid for | -| `spender` | `address` | Entity that can spend `account`'s tokens | -| `token` | `address` | Token address (ERC-7528 native token or ERC-20 contract) | -| `allowance` | `uint160` | Maximum allowed value to spend within each `period` | -| `period` | `uint48` | Time duration for resetting used `allowance` on a recurring basis (seconds) | -| `start` | `uint48` | Timestamp this spend permission is valid starting at (inclusive, unix seconds) | -| `end` | `uint48` | Timestamp this spend permission is valid until (exclusive, unix seconds) | -| `salt` | `uint256` | Arbitrary data to differentiate unique spend permissions with otherwise identical fields | -| `extraData` | `bytes` | Arbitrary data to attach to a spend permission which may be consumed by the `spender` | +| Название поля | Тип | Описание | +| -------------- | --------- | ---------------------------------------------------------------------------------------------------- | +| `account` | `address` | Смарт-аккаунт, для которого действительно данное разрешение на расходование | +| `spender` | `address` | Субъект, который может расходовать токены `account` | +| `token` | `address` | Адрес токена (нативный токен ERC-7528 или контракт ERC-20) | +| `allowance` | `uint160` | Максимальное допустимое значение для расходования в течение каждого `period` | +| `period` | `uint48` | Продолжительность времени для сброса использованного `allowance` на регулярной основе (в секундах) | +| `start` | `uint48` | Метка времени, начиная с которой разрешение действительно (включительно, Unix секунды) | +| `end` | `uint48` | Метка времени, до которой разрешение действительно (исключительно, Unix секунды) | +| `salt` | `uint256` | Произвольные данные для различения уникальных разрешений с идентичными остальными полями | +| `extraData` | `bytes` | Произвольные данные, прикрепляемые к разрешению, которые могут быть использованы стороной `spender` | ```tsx import { requestSpendPermission } from "@base-org/account/spend-permission"; @@ -52,7 +52,7 @@ const permission = await requestSpendPermission({ account: "0x...", spender: "0x...", token: "0x...", - chainId: 8453, // or any other supported chain + chainId: 8453, // или любой другая поддерживаемая цепь allowance: 1_000_000n, periodInDays: 30, provider: sdk.getProvider(), @@ -61,29 +61,29 @@ const permission = await requestSpendPermission({ console.log("Spend Permission:", permission); ``` -### Use the Spend Permission +### Использование разрешения на расходование -Using a permission is 2 steps: +Использование разрешения состоит из 2 шагов: -1. **Prepare the calls** — Call `prepareSpendCallData` with the permission and the requested `amount`. -2. **Submit the calls** — Submit the calls using your app's spender account. +1. **Подготовка вызовов** — Вызовите `prepareSpendCallData` с разрешением и запрашиваемой `amount`. +2. **Отправка вызовов** — Отправьте вызовы, используя смарт-аккаунт spender вашего приложения. -`prepareSpendCallData` returns an array of calls needed to spend the tokens: +`prepareSpendCallData` возвращает массив вызовов, необходимых для расходования токенов: -- `approveWithSignature` — When the permission is not yet registered onchain, this call would be prepended to the `spend` call. -- `spend` — The call to spend the tokens from the user's Base Account. +- `approveWithSignature` — Когда разрешение еще не зарегистрировано в блокчейне, этот вызов будет добавлен перед вызовом `spend`. +- `spend` — Вызов для расходования токенов из Base Account пользователя. ```tsx import { prepareSpendCallData } from "@base-org/account/spend-permission"; -// returns [approveWithSignatureCall, spendCall] +// возвращает [approveWithSignatureCall, spendCall] const spendCalls = await prepareSpendCallData({ permission, - amount, // optional; omit to spend the remaining allowance + amount, // опционально; опустите, чтобы потратить оставшийся лимит }); -// If your app spender account supports wallet_sendCalls, submit them in batch using wallet_sendCalls -// this is an example on how to do it using wallet_sendCalls in provider interface +// Если смарт-аккаунт spender вашего приложения поддерживает wallet_sendCalls, отправьте их пакетно, используя wallet_sendCalls +// это пример того, как это сделать через интерфейс provider await provider.request({ method: "wallet_sendCalls", params: [ @@ -96,8 +96,8 @@ await provider.request({ ], }); -// If your app spender account doesn't support wallet_sendCalls, submit them in order using eth_sendTransaction -// this is an example on how to do it using eth_sendTransaction in provider interface +// Если смарт-аккаунт spender вашего приложения не поддерживает wallet_sendCalls, отправьте их по порядку, используя eth_sendTransaction +// это пример того, как это сделать через интерфейс provider await Promise.all( spendCalls.map((call) => provider.request({ @@ -114,20 +114,20 @@ await Promise.all( ``` -**About the `spendCalls` array** +**О массиве `spendCalls`** -This array has 2 calls when submitting the permission onchain for *the first time*. -When the permission is already registered onchain, this array has only 1 call (the `spend` call). +Этот массив содержит 2 вызова при первой регистрации разрешения в блокчейне. +Когда разрешение уже зарегистрировано, массив содержит только 1 вызов (вызов `spend`). -For most use cases, you don't need to worry about this. +Для большинства случаев использования вам не нужно об этом беспокоиться. -### Revoke a Spend Permission +### Отзыв разрешения на расходование -You can revoke a permission in two ways: +Вы можете отозвать разрешение двумя способами: -- Request user approval via request to user's Base Account using `requestRevoke`. -- Revoke silently from your app's spender by submitting the call returned from `prepareRevokeCallData`. +- Запросить подтверждение пользователя через его Base Account с помощью `requestRevoke`. +- Отозвать автоматически со смарт-аккаунта spender вашего приложения, отправив вызов, возвращенный функцией `prepareRevokeCallData`. ```tsx import { @@ -135,7 +135,7 @@ import { prepareRevokeCallData, } from "@base-org/account/spend-permission"; -// Option A: User-initiated revoke (wallet popup) +// Вариант А: Отзыв, инициированный пользователем (всплывающее окно кошелька) try { const hash = await requestRevoke(permission); console.log("Revoke succeeded", hash); @@ -143,11 +143,11 @@ try { console.warn("Revoke was rejected or failed"); } -// Option B: Silent revoke by your app's spender account +// Вариант Б: Автоматический отзыв со смарт-аккаунта spender вашего приложения const revokeCall = await prepareRevokeCallData(permission); -// Submit the revoke call using your app's spender account -// this is an example on how to do it using wallet_sendCalls in provider interface +// Отправьте вызов отзыва, используя смарт-аккаунт spender вашего приложения +// это пример того, как это сделать через интерфейс provider await provider.request({ method: "wallet_sendCalls", params: [ @@ -160,8 +160,8 @@ await provider.request({ ], }); -// If your app spender account doesn't support wallet_sendCalls, submit the revoke call using eth_sendTransaction -// this is an example on how to do it using eth_sendTransaction in provider interface +// Если смарт-аккаунт spender вашего приложения не поддерживает wallet_sendCalls, отправьте вызов отзыва, используя eth_sendTransaction +// это пример того, как это сделать через интерфейс provider await provider.request({ method: "eth_sendTransaction", params: [ @@ -173,7 +173,7 @@ await provider.request({ }); ``` -## API Reference +## Справочник API - [requestSpendPermission](/base-account/reference/spend-permission-utilities/requestSpendPermission) - [prepareSpendCallData](/base-account/reference/spend-permission-utilities/prepareSpendCallData) @@ -183,7 +183,7 @@ await provider.request({ - [fetchPermission](/base-account/reference/spend-permission-utilities/fetchPermission) - [getPermissionStatus](/base-account/reference/spend-permission-utilities/getPermissionStatus) -## Complete Integration Example +## Пример полной интеграции ```typescript import { @@ -207,17 +207,17 @@ const sdk = createBaseAccountSDK({ const spender = "0xAppSpenderAddress"; -// 1) Fetch a specific permission by its hash -// Use fetchPermission when you already know the permission hash -// (e.g., stored from a previous session or passed as a parameter) +// 1) Получить конкретное разрешение по его хэшу +// Используйте fetchPermission, когда уже знаете хэш разрешения +// (например, сохраненный из предыдущей сессии или переданный как параметр) const permission = await fetchPermission({ permissionHash: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", provider: sdk.getProvider(), }); -// Alternative: Fetch all permissions for a spender -// Use fetchPermissions when you need to see all available permissions -// and want to choose which one to use +// Альтернатива: Получить все разрешения для spender +// Используйте fetchPermissions, когда нужно увидеть все доступные разрешения +// и выбрать, какое из них использовать // const permissions = await fetchPermissions({ // account: "0xUserBaseAccountAddress", // chainId: 84532, @@ -227,10 +227,10 @@ const permission = await fetchPermission({ // const permission = permissions.at(0); // ======================================== -// When there IS an existing permission +// Когда разрешение УЖЕ существует // ======================================== -// 2. check the status of permission +// 2. Проверить статус разрешения try { const { isActive, remainingSpend } = await getPermissionStatus(permission); const amount = 1000n; @@ -242,14 +242,14 @@ try { throw new Error("No spend permission available"); } -// 3. prepare the calls +// 3. Подготовить вызовы const [approveCall, spendCall] = await prepareSpendCallData({ permission, amount, }); -// 4. execute the calls using your app's spender account -// this is an example using wallet_sendCalls, in production it could be using eth_sendTransaction. +// 4. Выполнить вызовы, используя смарт-аккаунт spender вашего приложения +// это пример использования wallet_sendCalls, в продакшене можно использовать eth_sendTransaction. await provider.request({ method: "wallet_sendCalls", params: [ @@ -263,10 +263,10 @@ await provider.request({ }); // ======================================== -// When there is NOT an existing permission +// Когда разрешение НЕ существует // ======================================== -// 2. request a spend permission to use +// 2. Запросить разрешение на расходование для использования const newPermission = await requestSpendPermission({ account: "0xUserBaseAccountAddress", spender, @@ -277,14 +277,14 @@ const newPermission = await requestSpendPermission({ provider: sdk.getProvider(), }); -// 3. prepare the calls +// 3. Подготовить вызовы const spendCalls = await prepareSpendCallData({ permission: newPermission, amount: 1_000n, }); -// 4. execute the calls using your app's spender account -// this is an example using eth_sendTransaction. If your app account supports wallet_sendCalls, use wallet_sendCalls to batch the calls instead. +// 4. Выполнить вызовы, используя смарт-аккаунт spender вашего приложения +// это пример использования eth_sendTransaction. Если смарт-аккаунт вашего приложения поддерживает wallet_sendCalls, используйте wallet_sendCalls для пакетной отправки. await Promise.all( spendCalls.map((call) => provider.request({ @@ -300,7 +300,7 @@ await Promise.all( ); // ======================================== -// Request user to revoke spend permission +// Запросить у пользователя отзыв разрешения // ======================================== try { @@ -311,7 +311,7 @@ try { } // ======================================== -// Revoke spend permission in the background +// Отозвать разрешение в фоновом режиме // ======================================== const revokeCall = await prepareRevokeCallData(permission); @@ -329,11 +329,11 @@ await provider.request({ }); ``` -## Example Use Case +## Пример использования -Let's say you're building an AI agent that can autonomously purchase [Zora Creator Coins](https://docs.zora.co/coins) using secure [Spend Permissions](/base-account/improve-ux/spend-permissions) on Base. +Предположим, вы создаете AI-агента, который может автономно покупать [Zora Creator Coins](https://docs.zora.co/coins), используя безопасные [Spend Permissions](/base-account/improve-ux/spend-permissions) на Base. -This example demonstrates how to combine Base Account's [Spend Permissions](/base-account/improve-ux/spend-permissions) with Coinbase Developer Platform (CDP) [Server Wallets](https://docs.cdp.coinbase.com/server-wallets/v2/introduction/quickstart) and [Trade API](https://docs.cdp.coinbase.com/trade-api/quickstart) for seamless, gas-free AI agent transactions. +Этот пример демонстрирует, как объединить [Spend Permissions](/base-account/improve-ux/spend-permissions) Base Account с [Server Wallets](https://docs.cdp.coinbase.com/server-wallets/v2/introduction/quickstart) and [Trade API](https://docs.cdp.coinbase.com/trade-api/quickstart) от Coinbase Developer Platform (CDP) для бесперебойных, не требующих комиссий транзакций AI-агента. @@ -345,19 +345,19 @@ This example demonstrates how to combine Base Account's [Spend Permissions](/bas - Try the live application and see spend permissions in action + Протестируйте живое приложение и посмотрите, как работают разрешения на расходование - Explore the complete implementation on GitHub + Изучите полную реализацию на GitHub -**Learn more:** [AI Agent with Spend Permissions](/cookbook/spend-permissions-ai-agent) \ No newline at end of file +**Узнать больше:** [AI Agent with Spend Permissions](/cookbook/spend-permissions-ai-agent) diff --git a/docs/base-account/improve-ux/sponsor-gas/erc20-paymasters.mdx b/docs/base-account/improve-ux/sponsor-gas/erc20-paymasters.mdx index 4a23e867..8d9f11bf 100644 --- a/docs/base-account/improve-ux/sponsor-gas/erc20-paymasters.mdx +++ b/docs/base-account/improve-ux/sponsor-gas/erc20-paymasters.mdx @@ -1,25 +1,25 @@ --- -title: "Pay Gas in ERC20 tokens" -description: "Base Account enables users to pay for gas in ERC20 tokens" +title: "Оплата комиссий токенами ERC20" +description: "Base Account позволяет пользователям оплачивать комиссии (gas) токенами стандарта ERC20" --- -Base Account enables users to pay for gas in ERC20 tokens! -Tokens can be accepted for payment by passed in app paymasters in addition to a set of universally supported tokens, such as USDC (this set to be expanded soon). +Base Account позволяет пользователям оплачивать комиссии (gas) токенами стандарта ERC20! +Токены могут быть приняты в качестве оплаты через переданные в приложении paymaster'ы, в дополнение к набору универсально поддерживаемых токенов, таких как USDC (этот набор будет расширен в ближайшее время). -This guide outlines how to set up your own app paymaster which will accept your token as payment. +Это руководство описывает, как настроить собственный paymaster для вашего приложения, который будет принимать ваш токен в качестве оплаты. -### Choose a paymaster service provider +### Выберите провайдера услуги paymaster -As a prerequisite, you'll need to obtain a paymaster service URL from a paymaster service provider. ERC20 paymasters have additional requirements that will be outlined below. +В качестве предварительного условия вам необходимо получить URL службы paymaster от провайдера. Paymaster'ы для токенов ERC20 имеют дополнительные требования, которые будут описаны ниже. -We recommend the [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) paymaster as it is fully set up to work with Base Account ERC20 token gas payments out of the box. CDP is also offering up to $15k in gas credits as part of the [Base Gasless Campaign](/base-account/more/base-gasless-campaign). +Мы рекомендуем paymaster от [Coinbase Developer Platform](https://www.coinbase.com/developer-platform), поскольку он полностью готов к работе с оплатой комиссий токенами ERC20 в Base Account "из коробки". CDP также предлагает до $15 тыс. в виде грантов на газ в рамках [Base Gasless Campaign](/base-account/more/base-gasless-campaign). -Otherwise if using a different paymaster provider, it must conform to the specification outlined in [ERC20 Compatible Paymasters](#erc20-compatible-paymasters) to correctly work with Base Account. +Если вы используете другого провайдера paymaster, он должен соответствовать спецификации, изложенной в разделе [ERC20 Compatible Paymasters](#erc20-compatible-paymasters) чтобы корректно работать с Base Account. -### App setup for custom token +### Настройка приложения для пользовательского токена -Once you have a paymaster that is compatible with ERC20 gas payments on Base Account, you are only responsible for including the approvals to the paymaster for your token. It is recommended to periodically top up the allowance once they hit some threshold. +После того как у вас есть paymaster, совместимый с оплатой комиссий токенами ERC20 в Base Account, ваша задача - только включить разрешения (approvals) для вашего токена в адрес paymaster. Рекомендуется периодически пополнять разрешение, когда его остаток достигает определенного порога. ```js @@ -39,7 +39,7 @@ const mintTo = { calls = [mintTo] -// Checks for allowance +// Проверяем allowance (разрешенную сумму) const allowance = await client.readContract({ abi: parseAbi(["function allowance(address owner, address spender) returns (uint256)"]), address: tokenAddress, @@ -48,7 +48,7 @@ const allowance = await client.readContract({ }) if (allowance < minTokenThreshold) { - // include approval for $20 in calls so that the paymaster will be able to move the token to accept payment + // Добавляем вызов approve на $20 в список calls, чтобы paymaster мог переместить токены для принятия оплаты calls.push({ abi: ["function approve(address,uint)"], functionName: "approve", @@ -58,34 +58,34 @@ if (allowance < minTokenThreshold) { } ``` -That is it! Base Account will handle the rest as long as it is compatible as outlined below. +Это всё! Base Account позаботится об остальном, при условии что paymaster совместим, как описано ниже. -### ERC20 Compatible Paymasters +### Совместимые с ERC20 Paymaster -Coinbase Developer Platform is compatible out of the box and we will be working with other teams to include support soon! +Coinbase Developer Platform совместим "из коробки", и мы работаем с другими командами, чтобы вскоре добавить поддержку и у них! -The paymaster must handle the `pm_getPaymasterStubData` and `pm_getPaymasterData` JSON-RPC requests specified by ERC-7677 in addition to `pm_getAcceptedPaymentTokens`. We step through each request and response below. +Paymaster должен обрабатывать JSON-RPC запросы `pm_getPaymasterStubData` и `pm_getPaymasterData`, указанные в ERC-7677, в дополнение к `pm_getAcceptedPaymentTokens`. Мы разберем каждый запрос и ответ ниже. #### pm_getPaymasterStubData and pm_getPaymasterData -1. The paymaster must use the specified ERC20 for payment if specified in the 7677 context field under `erc20`. -2. Upon rejection / failure the paymaster should return a `data` field in the JSONRPC response which could be used to approve the paymaster and includes: +1. Paymaster должен использовать указанный токен ERC20 для оплаты, если он указан в поле контекста `erc20` согласно спецификации 7677. +2. При отказе / неудаче paymaster должен возвращать поле `data` в JSONRPC-ответе, которое может быть использовано для выдачи разрешения (approve) paymaster'у. Оно должно включать: -- `acceptedTokens` array which is a struct including the token address -- `paymasterAddress` field which is the paymaster address which will perform the token transfers. +- Массив `acceptedTokens`, который представляет собой структуру, содержащую адрес токена. +- Поле `paymasterAddress` - адрес paymaster'а, который будет выполнять перевод токенов. -3. Upon success the paymaster must return a `tokenPayment` field in the result. This includes: +3. При успехе paymaster должен возвращать поле `tokenPayment` в результате. Оно включает: -- `tokenAddress` address of the token used for payment -- `maxFee` the maximum fee to show in the UI -- `decimals` decimals to use in the UI -- `name` name of the token +- `tokenAddress` - адрес токена, использованного для оплаты. +- `maxFee` - максимальная комиссия для отображения в интерфейсе. +- `decimals` - количество знаков после запятой (децималы) для использования в интерфейсе. +- `name` - название токена. -Base Account will simulate the transaction to ensure success and accurate information. +Base Account выполнит симуляцию транзакции, чтобы убедиться в успехе и точности информации. -##### Request +##### Запрос -This is a standard V0.6 Entrypoint request example with the additional context for the specified token to be used. +Это пример стандартного запроса Entrypoint V0.6 с дополнительным контекстом для указания токена, который следует использовать. ```json { @@ -115,9 +115,9 @@ This is a standard V0.6 Entrypoint request example with the additional context f } ``` -##### Response +##### Ответ -Successful response: +Успешный ответ: ```json { @@ -135,7 +135,7 @@ Successful response: } ``` -Rejection response: +Ответ при отказе: ```json { @@ -158,10 +158,10 @@ Rejection response: #### pm_getAcceptedPaymentTokens -`pm_getAcceptedPaymentTokens` returns an array of tokens the paymaster will accept for payment. -The request contains the entrypoint and the chain id with optional context. +`pm_getAcceptedPaymentTokens` возвращает массив токенов, которые paymaster примет в качестве оплаты. +Запрос содержит адрес Entrypoint и идентификатор цепи (Chain ID) с опциональным контекстом. -##### Request +##### Запрос ```json { @@ -171,7 +171,7 @@ The request contains the entrypoint and the chain id with optional context. } ``` -##### Response +##### Ответ ```json { diff --git a/docs/base-account/improve-ux/sponsor-gas/paymasters.mdx b/docs/base-account/improve-ux/sponsor-gas/paymasters.mdx index 27efde08..6f6e1f3d 100644 --- a/docs/base-account/improve-ux/sponsor-gas/paymasters.mdx +++ b/docs/base-account/improve-ux/sponsor-gas/paymasters.mdx @@ -1,32 +1,31 @@ --- -title: "Sponsor Gas" -description: "Use Paymasters to sponsor your users' transactions" +title: "Спонсирование комиссий" +description: "Используйте Paymaster'ы для спонсирования транзакций ваших пользователей" --- -One of the biggest UX enhancements unlocked by Base Account is the ability for app developers to sponsor their users' transactions. -If your app supports Base Account, you can start sponsoring your users' -transactions by using [standardized Paymaster service communication](https://erc7677.xyz) enabled by [new wallet RPC methods](https://eip5792.xyz). +Одним из ключевых улучшений пользовательского опыта, которое предоставляет Base Account, является возможность для разработчиков приложений спонсировать транзакции своих пользователей. +Если ваше приложение поддерживает Base Account, вы можете начать спонсировать транзакции пользователей, используя [стандартизированную коммуникацию со службой Paymaster](https://erc7677.xyz) обеспечиваемую [новыми RPC-методами кошелька](https://eip5792.xyz). -This guide is specific to using Base Account, you can find our more about using Paymasters with Base in -the [Base Go Gasless page](/cookbook/go-gasless). +Данное руководство специфично для использования Base Account. Более подробную информацию об использовании Paymaster'ов на Base вы можете найти +на странице [Base Go Gasless page](/cookbook/go-gasless). -## Implementation Guide +## Руководство по реализации - - As a prerequisite, you'll need to obtain a Paymaster service URL from a Paymaster service provider. + + В качестве предварительного условия вам необходимо получить URL службы Paymaster от провайдера этой услуги. - We'll use [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) as a Paymaster service provider, - currently offering up to $15k in gas credits as part of the [Base Gasless Campaign](/base-account/more/base-gasless-campaign). + Мы будем использовать [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) в качестве провайдера услуг Paymaster, + который в настоящее время предлагает до $15 тыс. в виде грантов на газ в рамках [Base Gasless Campaign](/base-account/more/base-gasless-campaign). - **ERC-7677-Compliant Paymaster Providers** + **Провайдеры Paymaster, совместимые с ERC-7677** - If you choose to use a different Paymaster service provider, ensure they are [ERC-7677-compliant](https://www.erc7677.xyz/ecosystem/paymasters). + Если вы решите использовать другого провайдера услуг Paymaster, убедитесь, что он [совместим с ERC-7677](https://www.erc7677.xyz/ecosystem/paymasters). - Once you have signed up for [Coinbase Developer Platform](https://www.coinbase.com/developer-platform), you get your Paymaster service URL by navigating to **Onchain Tools > Paymaster** as shown below: + После регистрации в [Coinbase Developer Platform](https://www.coinbase.com/developer-platform), вы получите URL вашей службы Paymaster, перейдя в раздел **Onchain Tools > Paymaster**, как показано ниже:
@@ -37,20 +36,20 @@ the [Base Go Gasless page](/cookbook/go-gasless). loading="lazy" /> - How to get your Paymaster service URL + Как получить URL вашей службы Paymaster
- **Should you create a proxy for your Paymaster service?** + **Стоит ли создавать прокси для вашей службы Paymaster?** - We recommend using a proxy to protect the Paymaster service URL to prevent it from being exposed/leaked on a frontend client. + Мы рекомендуем использовать прокси для защиты URL службы Paymaster, чтобы предотвратить его раскрытие/утечку на клиентской стороне (frontend). - For local development, you can use the same URL for the Paymaster service and the proxy. + Для локальной разработки вы можете использовать один и тот же URL для службы Paymaster и прокси. - Once you have your Paymaster service URL, you can proceed to setting up your contracts allowlist. - This is a list of contracts and function calls that you want to be sponsored by the Paymaster. + Получив URL службы Paymaster, вы можете перейти к настройке разрешительного списка (allowlist) контрактов. + Это список контрактов и вызовов функций, которые вы хотите, чтобы Paymaster спонсировал.
@@ -61,27 +60,27 @@ the [Base Go Gasless page](/cookbook/go-gasless). loading="lazy" /> - How to set your Paymaster contracts allowlist + Как настроить разрешительный список контрактов Paymaster
- Congrats! You've set up your Paymaster service and contracts allowlist. - It's time to set up the Base Account SDK. + Поздравляем! Вы настроили службу Paymaster и разрешительный список контрактов. + Пришло время настроить SDK для Base Account. - **You can also choose to create custom advanced policies !** + **Вы также можете создать собственные расширенные политики!** - You can create a `willSponsor` function to add some extra validation if you need more control over the policy enforcement. + При необходимости более тонкого контроля над применением политик вы можете создать функцию `willSponsor` для дополнительной валидации. - `willSponsor` is most likely not needed if you are using [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) as it has built-in policy enforcement features, - but know that this is still possible if you need it. + Скорее всего, функция `willSponsor` не понадобится, если вы используете [Coinbase Developer Platform](https://www.coinbase.com/developer-platform)так как он имеет встроенные функции применения политик, + но знайте, что эта возможность всё равно доступна, если она вам нужна.
- - Install and initialize the Base Account SDK to interact with Base Account: + + Установите и инициализируйте SDK Base Account для взаимодействия со смарт-аккаунтом: - ### Installation + ### Установка ```bash npm @@ -101,7 +100,7 @@ the [Base Go Gasless page](/cookbook/go-gasless). ``` - ### Initialize the SDK + ### Инициализация SDK ```tsx import { createBaseAccountSDK, base } from '@base-org/account'; @@ -109,32 +108,32 @@ the [Base Go Gasless page](/cookbook/go-gasless). const sdk = createBaseAccountSDK({ appName: 'Paymaster Demo', appLogoUrl: 'https://base.org/logo.png', - appChainIds: [base.constants.CHAIN_IDS.baseSepolia], // or base.constants.CHAIN_IDS.base for mainnet + appChainIds: [base.constants.CHAIN_IDS.baseSepolia], // или base.constants.CHAIN_IDS.base для мейннета }); const provider = sdk.getProvider(); ``` - - Once you have your Paymaster service set up, you can now use `wallet_sendCalls` with paymaster capabilities to sponsor transactions. + + После настройки службы Paymaster вы можете использовать метод `wallet_sendCalls` с возможностями paymaster для спонсирования транзакций. - **Pass in the proxy URL** + **Передавайте URL прокси** - If you set up a proxy in your app's backend as recommended in step (1) above, you'll want to pass in the proxy URL you created. + Если вы настроили прокси в бэкенде вашего приложения, как рекомендуется в шаге (1) выше, вам нужно передать созданный вами URL прокси. - ### Basic Sponsored Transaction + ### Базовая спонсируемая транзакция - Here's how to send a sponsored transaction using the `wallet_sendCalls` RPC method: + Вот как отправить спонсируемую транзакцию с помощью RPC-метода `wallet_sendCalls`: ```tsx import { createBaseAccountSDK, getCryptoKeyAccount, base } from '@base-org/account'; import { numberToHex, encodeFunctionData, parseEther } from 'viem'; - // Example NFT contract ABI + // Пример ABI контракта NFT const nftABI = [ { name: 'safeMint', @@ -155,7 +154,7 @@ the [Base Go Gasless page](/cookbook/go-gasless). const provider = sdk.getProvider(); try { - // Get the user's account + // Получаем аккаунт пользователя const cryptoAccount = await getCryptoKeyAccount(); const fromAddress = cryptoAccount?.account?.address; @@ -163,10 +162,10 @@ the [Base Go Gasless page](/cookbook/go-gasless). throw new Error('No account found'); } - // Your Paymaster service URL (use your proxy URL) + // URL вашей службы Paymaster (используйте URL вашего прокси) const paymasterServiceUrl = process.env.NEXT_PUBLIC_PAYMASTER_PROXY_SERVER_URL; - // Prepare the transaction call + // Подготавливаем вызов транзакции const nftAddress = '0x119Ea671030FBf79AB93b436D2E20af6ea469a19'; const calls = [ { @@ -180,7 +179,7 @@ the [Base Go Gasless page](/cookbook/go-gasless). } ]; - // Send the transaction with paymaster capabilities + // Отправляем транзакцию с возможностями paymaster const result = await provider.request({ method: 'wallet_sendCalls', params: [{ @@ -205,9 +204,9 @@ the [Base Go Gasless page](/cookbook/go-gasless). } ``` - ### Multiple Sponsored Transactions + ### Несколько спонсируемых транзакций - You can also batch multiple transactions and have them all sponsored: + Вы также можете объединить несколько транзакций в пакет (batch), и все они будут спонсированы: ```tsx async function sendMultipleSponsoredTransactions() { @@ -223,17 +222,17 @@ the [Base Go Gasless page](/cookbook/go-gasless). const paymasterServiceUrl = process.env.NEXT_PUBLIC_PAYMASTER_PROXY_SERVER_URL; - // Multiple calls in a single sponsored transaction + // Несколько вызовов в одной спонсируемой транзакции const calls = [ { to: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', value: numberToHex(parseEther('0.001')), - data: '0x' // Simple ETH transfer + data: '0x' // Простой перевод ETH }, { to: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E456', value: numberToHex(parseEther('0.001')), - data: '0x' // Another ETH transfer + data: '0x' // Еще один перевод ETH } ]; @@ -256,9 +255,9 @@ the [Base Go Gasless page](/cookbook/go-gasless). } ``` - ### Check Paymaster Capabilities + ### Проверка поддержки Paymaster - Before sending sponsored transactions, you can check if the wallet supports paymaster services: + Перед отправкой спонсируемых транзакций вы можете проверить, поддерживает ли кошелек услуги paymaster: ```tsx async function checkPaymasterSupport() { @@ -294,8 +293,8 @@ the [Base Go Gasless page](/cookbook/go-gasless). } ``` - That's it! Base Account will handle the rest. If your Paymaster service is able to sponsor the transaction, - in the UI Base Account will indicate to your user that the transaction is sponsored. + Вот и всё! Base Account позаботится обо всём остальном. Если ваша служба Paymaster может спонсировать транзакцию, + в интерфейсе Base Account укажет вашему пользователю, что транзакция спонсируется.
diff --git a/docs/base-account/improve-ux/sub-accounts.mdx b/docs/base-account/improve-ux/sub-accounts.mdx index 7c50b6b0..24af18e9 100644 --- a/docs/base-account/improve-ux/sub-accounts.mdx +++ b/docs/base-account/improve-ux/sub-accounts.mdx @@ -1,37 +1,37 @@ --- -title: 'Use Sub Accounts' -description: 'Learn how to create and use Sub Accounts using Base Account SDK' +title: 'Использование суб-аккаунтов' +description: 'Узнайте, как создавать и использовать суб-аккаунты с помощью SDK Base Account' --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx" -## What are Sub Accounts? +## Что такое суб-аккаунты? -Sub Accounts allow you to provision app-specific wallet accounts for your users that are embedded directly in your application. Once created, you can interact with them just as you would with any other wallet via the wallet provider or popular onchain libraries like OnchainKit, wagmi, and viem. +Суб-аккаунты (Sub Accounts) позволяют создавать для ваших пользователей специфичные для приложения кошельки, которые встроены непосредственно в ваше приложение. После создания вы можете взаимодействовать с ними так же, как и с любым другим кошельком, через провайдер кошелька или популярные ончейн-библиотеки, такие как OnchainKit, wagmi и viem. -Looking for a full implementation? Jump to the [Complete Integration Example](/base-account/improve-ux/sub-accounts#complete-integration-example). +Ищете полную реализацию? Перейдите к [Complete Integration Example](/base-account/improve-ux/sub-accounts#complete-integration-example). -## Key Benefits +## Ключевые преимущества -- **Frictionless transactions**: Eliminate repeated signing prompts for high frequency and agentic use cases or take full control of the transaction flow. -- **No funding flows required**: Spend Permissions allow Sub Accounts to spend directly from the universal Base Account's balance. -- **User control**: Users can manage all their sub accounts at [account.base.app](https://account.base.app). +- **Беспрепятственные транзакции**: Устраните повторяющиеся запросы на подпись для сценариев с высокой частотой операций или автономных агентов (AI agents) или возьмите полный контроль над процессом транзакции. +- **Не требуются пополнения**: Разрешения на расходование (Spend Permissions) позволяют суб-аккаунтам тратить средства напрямую с баланса универсального Base Account пользователя. +- **Контроль со стороны пользователя**: Пользователи могут управлять всеми своими суб-аккаунтами на [account.base.app](https://account.base.app). -If you would like to see a live demo of Sub Accounts in action, check out our [Sub Accounts Demo](https://sub-accounts-fc.vercel.app). +Если вы хотите увидеть живую демонстрацию работы суб-аккаунтов, ознакомьтесь с нашим [Sub Accounts Demo](https://sub-accounts-fc.vercel.app). **Spend Permissions** -Sub Accounts are optimized for use with Spend Permissions to allow your app to take advantage of the user's existing Base Account balances. See the [Spend Permissions](/base-account/improve-ux/spend-permissions) guide for more information about how they work. +Суб-аккаунты оптимизированы для использования вместе с Разрешениями на расходование (Spend Permissions), что позволяет вашему приложению использовать существующие балансы Base Account пользователя. Подробнее о том, как это работает, читайте в руководстве по [Spend Permissions](/base-account/improve-ux/spend-permissions). -## Installation +## Установка -Install the Base Account SDK: +Установите SDK Base Account: ```bash npm @@ -51,9 +51,9 @@ bun add @base-org/account ``` -## Quickstart +## Быстрый старт -The fastest way to adopt Sub Accounts is to set `creation` to `on-connect` and `defaultAccount` to `sub` in the SDK configuration. +Самый быстрый способ начать использовать суб-аккаунты - установить для параметров конфигурации SDK значения `creation`: `on-connect` и `defaultAccount`: `sub`. ```tsx const sdk = createBaseAccountSDK({ @@ -65,52 +65,52 @@ const sdk = createBaseAccountSDK({ }); ``` -This will automatically create a Sub Account for the user when they connect their Base Account and transactions will automatically be sent from the Sub Account unless you specify the `from` parameter in your transaction request to be the universal account address. Spend Permissions will also be automatically requested for the Sub Account as your app needs them. +Это автоматически создаст суб-аккаунт для пользователя при подключении его Base Account, и транзакции будут автоматически отправляться с этого суб-аккаунта, если вы не укажете в запросе транзакции параметр `from` как адрес универсального аккаунта. Разрешения на расходование также будут автоматически запрашиваться для суб-аккаунта по мере необходимости вашему приложению. -This is what the user will see when they connect their Base Account and automatic Sub Accounts are enabled: +Вот что увидит пользователь при подключении своего Base Account, когда включены автоматические суб-аккаунты:
Sub Account Creation Flow
-We recommend using a [Paymaster](/base-account/improve-ux/sponsor-gas/paymasters) to sponsor gas to ensure the best user experience when integrating Sub Accounts. You can set a paymaster to be used for all transactions by configuring the `paymasterUrls` parameter in the SDK configuration. See the [createBaseAccount](/base-account/reference/core/createBaseAccount#param-paymaster-urls) reference for more information. +Мы рекомендуем использовать [Paymaster](/base-account/improve-ux/sponsor-gas/paymasters) для спонсирования комиссий, чтобы обеспечить наилучший пользовательский опыт при интеграции суб-аккаунтов. Вы можете настроить paymaster для использования во всех транзакциях, указав параметр `paymasterUrls` в конфигурации SDK. Подробнее см. в справочнике по [createBaseAccount](/base-account/reference/core/createBaseAccount#param-paymaster-urls). -## Using Sub Accounts +## Использование суб-аккаунтов -### Initialize the SDK +### Инициализация SDK -First, set up the Base Account SDK. Be sure to customize the `appName` and `appLogoUrl` to match your app as this will be displayed in the wallet connection popup and in the account.base.app dashboard. You can also customize the `appChainIds` to be the chains that your app supports. +Сначала настройте SDK Base Account. Обязательно укажите `appName` и `appLogoUrl`, соответствующие вашему приложению, так как они будут отображаться во всплывающем окне подключения кошелька и в панели управления account.base.app. Вы также можете настроить `appChainIds` на цепи, которые поддерживает ваше приложение. ```tsx import { createBaseAccountSDK, getCryptoKeyAccount } from '@base-org/account'; import { base } from 'viem/chains'; -// Initialize SDK with Sub Account configuration +// Инициализация SDK с конфигурацией суб-аккаунта const sdk = createBaseAccountSDK({ appName: 'Base Account SDK Demo', appLogoUrl: 'https://base.org/logo.png', appChainIds: [base.id], }); -// Get an EIP-1193 provider +// Получить провайдер EIP-1193 const provider = sdk.getProvider() ``` -### Create a Sub Account +### Создание суб-аккаунта -Make sure to authenticate the user with their Base Account before creating a Sub Account. -For that, you can choose one of the following options: -- Follow the [Authenticate users](/base-account/guides/authenticate-users) guide -- Simply use `provider.request({ method: 'eth_requestAccounts' });` for a simple wallet connection +Убедитесь, что пользователь аутентифицирован с помощью своего Base Account перед созданием суб-аккаунта. +Для этого вы можете выбрать один из следующих вариантов: +- Следуйте руководству [Authenticate users](/base-account/guides/authenticate-users) +- Или просто используйте `provider.request({ method: 'eth_requestAccounts' });` для простого подключения кошелька -Create a Sub Account for your application using the provider's [wallet_addSubAccount](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount) RPC method. When no `publicKey` parameter is provided, a non-extractable browser CryptoKey is generated and used to sign on behalf of the Sub Account. +Создайте суб-аккаунт для вашего приложения, используя RPC-метод провайдера [wallet_addSubAccount](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount). Когда параметр `publicKey` не указан, генерируется неизвлекаемый ключ браузера (CryptoKey), который используется для подписи от имени суб-аккаунта. ```tsx -// Create sub account +// Создать суб-аккаунт const subAccount = await provider.request({ method: 'wallet_addSubAccount', params: [ @@ -125,7 +125,7 @@ const subAccount = await provider.request({ console.log('Sub Account created:', subAccount.address); ``` -Alternatively, you can use the SDK convenience method: +Альтернативно, вы можете использовать удобный метод SDK: ```tsx const subAccount = await sdk.subAccount.create(); @@ -133,24 +133,24 @@ const subAccount = await sdk.subAccount.create(); console.log('Sub Account created:', subAccount.address); ``` -This is what the user will see when prompted to create a Sub Account: +Вот что увидит пользователь при запросе на создание суб-аккаунта:
Sub Account Creation Flow
-### Get Existing Sub Account +### Получение существующего суб-аккаунта -Retrieve an existing Sub Account using the provider's [wallet_getSubAccounts](/base-account/reference/core/provider-rpc-methods/wallet_getSubAccounts) RPC method. This will return the Sub Account associated with the app's domain and is useful to check if a Sub Account already exists for the user to determine if one needs to be created. +Получите существующий суб-аккаунт, используя RPC-метод провайдера [wallet_getSubAccounts](/base-account/reference/core/provider-rpc-methods/wallet_getSubAccounts). Это вернет суб-аккаунт, связанный с доменом приложения, и полезно для проверки существования суб-аккаунта у пользователя, чтобы определить, нужно ли его создавать. ```tsx -// Get the universal account +// Получить универсальный аккаунт const [universalAddress] = await provider.request({ method: "eth_requestAccounts", params: [] }) -// Get sub account for universal account +// Получить суб-аккаунт для универсального аккаунта const { subAccounts: [subAccount] } = await provider.request({ method: 'wallet_getSubAccounts', params: [{ @@ -166,33 +166,33 @@ if (subAccount) { } ``` -Alternatively, you can use the SDK convenience method: +Альтернативно, вы можете использовать удобный метод SDK: ```tsx const subAccount = await sdk.subAccount.get(); console.log('Sub Account:', subAccount); ``` -### Send transactions +### Отправка транзакций -To send transactions from the connected sub account you can use EIP-5792 `wallet_sendCalls` or `eth_sendTransaction`. You need to specify the `from` parameter to be the sub account address. +Чтобы отправлять транзакции с подключенного суб-аккаунта, вы можете использовать `wallet_sendCalls` (EIP-5792) или `eth_sendTransaction`. Вам необходимо указать параметр `from` как адрес суб-аккаунта. -When the Sub Account is connected, it is the second account in the array returned by `eth_requestAccounts` or `eth_accounts`. `wallet_addSubAccount` needs to be called in each session before the Sub Account can be used. It will not trigger a new Sub Account creation if one already exists. +Когда суб-аккаунт подключен, он является вторым аккаунтом в массиве, возвращаемом `eth_requestAccounts` или `eth_accounts`. Метод `wallet_addSubAccount` необходимо вызывать в каждой сессии перед использованием суб-аккаунта. Это не вызовет новое создание суб-аккаунта, если он уже существует. -If you are using `mode: 'auto'`, the Sub Account will be the first account in the array. +Если вы используете `mode: 'auto'`, суб-аккаунт будет первым аккаунтом в массиве. -First, get all the accounts that are available, of which the sub account will be the second account: +Сначала получите все доступные аккаунты, где суб-аккаунт будет вторым: ```tsx const [universalAddress, subAccountAddress] = await provider.request({ - method: "eth_requestAccounts", // or "eth_accounts" if already connected + method: "eth_requestAccounts", // или "eth_accounts", если уже подключен params: [] }) ``` -Then, send the transaction from the sub account: +Затем отправьте транзакцию от имени суб-аккаунта: **`wallet_sendCalls`** @@ -202,7 +202,7 @@ const callsId = await provider.request({ params: [{ version: "2.0", atomicRequired: true, - from: subAccountAddress, // Specify the sub account address + from: subAccountAddress, // Указываем адрес суб-аккаунта calls: [{ to: '0x...', data: '0x...', @@ -224,7 +224,7 @@ console.log('Calls sent:', callsId); const tx = await provider.request({ method: 'eth_sendTransaction', params: [{ - from: subAccountAddress, // Specify the sub account address + from: subAccountAddress, // Указываем адрес суб-аккаунта to: '0x...', data: '0x...', value: '0x...', @@ -234,13 +234,13 @@ const tx = await provider.request({ console.log('Transaction sent:', tx); ``` -We recommend using `wallet_sendCalls` in conjunction with a paymaster to ensure the best user experience. See the [Paymasters](/base-account/improve-ux/sponsor-gas/paymasters) guide for more information. +Мы рекомендуем использовать `wallet_sendCalls` вместе с paymaster для обеспечения наилучшего пользовательского опыта. Подробнее см. в руководстве по [Paymasters](/base-account/improve-ux/sponsor-gas/paymasters). -## Advanced Usage +## Расширенное использование -### Import an existing account +### Импорт существующего аккаунта -If you already have a deployed Smart Contract Account and would like to turn it into a Sub Account of the connected Base Account, you can import it as a Sub Account using the provider RPC method: +Если у вас уже есть развернутый смарт-контракт аккаунт, и вы хотите сделать его суб-аккаунтом подключенного Base Account, вы можете импортировать его как суб-аккаунт, используя RPC-метод провайдера: ```tsx const subAccount = await provider.request({ @@ -250,7 +250,7 @@ const subAccount = await provider.request({ account: { type: 'deployed', address: '0xYourSmartContractAccountAddress', - chainId: 8453 // the chain the account is deployed on + chainId: 8453 // цепь, на которой развернут аккаунт }, } ], @@ -261,18 +261,17 @@ console.log('Sub Account added:', subAccount.address); -Before the Sub Account is imported, you will need to add the Base Account address as an owner of the Sub Account. This currently needs to be done manually -by calling the [`addOwnerAddress`](https://github.com/coinbase/smart-wallet/blob/a8c6456f3a6d5d2dea08d6336b3be13395cacd42/src/MultiOwnable.sol#L101) or [`addOwnerPublicKey`](https://github.com/coinbase/smart-wallet/blob/a8c6456f3a6d5d2dea08d6336b3be13395cacd42/src/MultiOwnable.sol#L109) functions on the Smart Contract of the Sub Account that was imported and setting the Base Account address as the owner. +Перед импортом суб-аккаунта вам необходимо добавить адрес Base Account в качестве владельца (owner) суб-аккаунта. В настоящее время это необходимо делать вручную путем вызова функций [`addOwnerAddress`](https://github.com/coinbase/smart-wallet/blob/a8c6456f3a6d5d2dea08d6336b3be13395cacd42/src/MultiOwnable.sol#L101) или [`addOwnerPublicKey`](https://github.com/coinbase/smart-wallet/blob/a8c6456f3a6d5d2dea08d6336b3be13395cacd42/src/MultiOwnable.sol#L109) в смарт-контракте импортируемого суб-аккаунта, указав адрес Base Account в качестве владельца. -Additionally, only Coinbase Smart Wallet contracts are currently supported for importing as a Sub Account into your Base Account. +Кроме того, на данный момент только контракты Coinbase Smart Wallet поддерживаются для импорта в качестве суб-аккаунта в ваш Base Account. -The Coinbase Smart Wallet contract ABI can be found on [GitHub](https://github.com/base/account-sdk/blob/master/packages/account-sdk/src/sign/base-account/utils/constants.ts#L8). +ABI контракта Coinbase Smart Wallet можно найти на [GitHub](https://github.com/base/account-sdk/blob/master/packages/account-sdk/src/sign/base-account/utils/constants.ts#L8). -### Add Owner Account +### Добавление владельца (Owner) аккаунта -Sub Accounts automatically detect when an ownership update is needed when a signature is required and will prompt the user to approve the update before signing. However, you can also add an owner to a Sub Account manually using the SDK convenience method: +Суб-аккаунты автоматически обнаруживают необходимость обновления прав владения, когда требуется подпись, и запрашивают у пользователя подтверждение перед подписанием. Однако вы также можете добавить владельца к суб-аккаунту вручную, используя удобный метод SDK: ```tsx const ownerAccount = await sdk.subAccount.addOwner({ @@ -284,43 +283,43 @@ const ownerAccount = await sdk.subAccount.addOwner({ console.log('Owner added to Sub Account'); ``` -This generates a transaction to call the `addOwnerAddress` or `addOwnerPublicKey` functions on the Sub Account's smart contract to add the owner. +Это создает транзакцию для вызова функций `addOwnerAddress` или `addOwnerPublicKey` в смарт-контракте суб-аккаунта, чтобы добавить владельца. -Ownership changes are expected if the user signs in to your app on a new device or browser. +Изменения прав владения ожидаемы, если пользователь входит в ваше приложение на новом устройстве или в другом браузере. -Ensure you do not lose your app's Sub Account signer keys when using the SDK on the server (e.g. Node.js) as updating the owner requires a signature from the user, which cannot be requested from server contexts. +Убедитесь, что вы не теряете ключи для подписи суб-аккаунта вашего приложения при использовании SDK на сервере (например, Node.js), так как обновление владельца требует подписи от пользователя, которую нельзя запросить в серверном контексте. -## Auto Spend Permissions +## Автоматические разрешения на расходование (Auto Spend Permissions) -Auto Spend Permissions allows Sub Accounts to access funds from their parent Base Account when transaction balances are insufficient. This feature can also establish ongoing spend permissions, enabling future transactions to execute without user approval prompts, reducing friction in your app's transaction flow. +Функция Auto Spend Permissions позволяет суб-аккаунтам получать доступ к средствам из их родительского Base Account, когда баланса суб-аккаунта недостаточно для транзакции. Эта функция также может устанавливать постоянные разрешения на расходование, позволяя выполнять будущие транзакции без запросов на подтверждение пользователя, что снижает трение в процессе транзакций вашего приложения. -This feature is **enabled by default** when using Sub Accounts. +Эта функция **включена по умолчанию** при использовании суб-аккаунтов. -### How it works +### Как это работает -**First-time transaction flow:** -When a Sub Account attempts its first transaction, Base Account displays a popup for user approval. During this approval process, Base Account: +**Поток первой транзакции:** +Когда суб-аккаунт пытается совершить свою первую транзакцию, Base Account отображает всплывающее окно для подтверждения пользователем. В процессе этого подтверждения Base Account: -- Automatically detects any missing tokens (native or ERC-20) needed for the transaction -- Requests a transfer of the required funds from the parent Base Account to the Sub Account to fulfill the current transaction -- Allows the user to optionally grant ongoing spend permissions for future transactions in that token +- Автоматически определяет отсутствующие токены (нативные или ERC-20), необходимые для транзакции +- Запрашивает перевод необходимых средств из родительского Base Account в суб-аккаунт для выполнения текущей транзакции +- Позволяет пользователю при желании предоставить постоянные разрешения на расходование для будущих транзакций в этом токене -**Subsequent transactions:** -If the user granted spend permissions, future transactions follow this priority: +**Последующие транзакции:** +Если пользователь предоставил разрешения на расходование, будущие транзакции следуют такому приоритету: -1. First, attempt using existing Sub Account balances and granted spend permissions -2. If insufficient, prompt the user to authorize additional transfers and/or spend permissions from their Base Account +1. Сначала используется существующий баланс суб-аккаунта и предоставленные разрешения на расходование +2. Если средств недостаточно, пользователю предлагается авторизовать дополнительные переводы и/или разрешения на расходование со своего Base Account -Spend permission requests are limited to the first token when multiple transfers are needed for a single transaction. Additional tokens require separate approvals. +Запросы на разрешение расходования ограничены первым токеном, когда для одной транзакции требуется несколько переводов. Для дополнительных токенов требуются отдельные разрешения. -### Configuration +### Конфигурация -If your users' Sub Accounts will be funded manually, you can disable Auto Spend Permissions by setting `funding` to `manual` in your SDK configuration: +Если суб-аккаунты ваших пользователей будут пополняться вручную, вы можете отключить Auto Spend Permissions, установив для параметра `funding` значение `manual` в конфигурации SDK: ```tsx const sdk = createBaseAccountSDK({ @@ -328,24 +327,24 @@ const sdk = createBaseAccountSDK({ appLogoUrl: 'https://base.org/logo.png', appChainIds: [base.id], subAccounts: { - funding: 'manual', // Disable auto spend permissions + funding: 'manual', // Отключить автоматические разрешения на расходование } }); ``` -## Technical Details +## Технические детали -Base Account's self-custodial design requires a user passkey prompt for each wallet interaction, such as transactions or message signing. While this ensures user awareness and approval of every wallet interaction, it can impact user experience in applications requiring frequent wallet interactions. +Самокастодиальный дизайн Base Account требует запроса на подтверждение с помощью passkey для каждого взаимодействия с кошельком, такого как транзакции или подпись сообщений. Хотя это обеспечивает осведомленность и одобрение пользователем каждого действия, это может повлиять на пользовательский опыт в приложениях, требующих частых взаимодействий с кошельком. -To support Base Account with user experiences that need more developer control over wallet interactions, we've built Sub Accounts in conjunction with [ERC-7895](https://eip.tools/eip/7895), a new wallet RPC for creating hierarchical relationships between wallet accounts. +Для поддержки Base Account в сценариях, где разработчикам требуется больший контроль над взаимодействиями с кошельком, мы создали суб-аккаунты совместно с [ERC-7895](https://eip.tools/eip/7895) - новым RPC-методом кошелька для создания иерархических отношений между аккаунтами кошельков. -These Sub Accounts are linked to the end user's Base Account through an onchain relationship. When combined with our [Spend Permission feature](/base-account/improve-ux/spend-permissions), this creates a powerful foundation for provisioning and funding app accounts securely, while giving you ample control over building the user experience that makes the most sense for your application. +Эти суб-аккаунты связаны с Base Account конечного пользователя через ончейн-отношения. В сочетании с нашей функцией [Spend Permission](/base-account/improve-ux/spend-permissions) это создает мощную основу для безопасного создания и финансирования аккаунтов приложений, предоставляя вам широкий контроль для создания оптимального пользовательского опыта. -## Complete Integration Example +## Пример полной интеграции -Here's a full React component that demonstrates Sub Account creation and usage: +Вот полный React-компонент, демонстрирующий создание и использование суб-аккаунта: ```tsx import { createBaseAccountSDK } from "@base-org/account"; @@ -379,7 +378,7 @@ export default function SubAccountDemo() { const [loadingUniversal, setLoadingUniversal] = useState(false); const [status, setStatus] = useState(""); - // Initialize SDK and crypto account + // Инициализация SDK и криптоаккаунта useEffect(() => { const initializeSDK = async () => { try { @@ -388,7 +387,7 @@ export default function SubAccountDemo() { appChainIds: [baseSepolia.id], }); - // Get the provider + // Получить провайдер const providerInstance = sdkInstance.getProvider(); setProvider(providerInstance); @@ -412,7 +411,7 @@ export default function SubAccountDemo() { setStatus("Connecting wallet..."); try { - // Connect to the wallet + // Подключиться к кошельку const accounts = (await provider.request({ method: "eth_requestAccounts", params: [], @@ -422,7 +421,7 @@ export default function SubAccountDemo() { setUniversalAddress(universalAddr); setConnected(true); - // Check for existing sub account + // Проверить наличие существующего суб-аккаунта const response = (await provider.request({ method: "wallet_getSubAccounts", params: [ @@ -500,7 +499,7 @@ export default function SubAccountDemo() { { version: "2.0", atomicRequired: true, - chainId: `0x${baseSepolia.id.toString(16)}`, // Convert to hex + chainId: `0x${baseSepolia.id.toString(16)}`, // Конвертировать в hex from, calls, capabilities: { @@ -669,4 +668,4 @@ export default function SubAccountDemo() {
); } -``` \ No newline at end of file +``` diff --git a/docs/base-account/more/base-gasless-campaign.mdx b/docs/base-account/more/base-gasless-campaign.mdx index 224d3e80..32811e42 100644 --- a/docs/base-account/more/base-gasless-campaign.mdx +++ b/docs/base-account/more/base-gasless-campaign.mdx @@ -1,14 +1,14 @@ --- -title: "Base Gasless Campaign" +title: "Кампания Base Gasless" --- -Base is offering gas credits to help developers make the most of -Base Account's [paymaster (sponsored transactions)](/base-account/improve-ux/sponsor-gas/paymasters) features. +Base предлагает газовые кредиты, чтобы помочь разработчикам максимально +использовать возможности Base Account [paymaster (спонсируемых транзакций)](/base-account/improve-ux/sponsor-gas/paymasters). -| Partner Tier | Base Gas Credit Incentive | Requirements | Actions | +| Уровень партнёрства | Стимул: Газовый кредит от Base | Требования | Действия | | ------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1 | $15k |
  • - Support Base Account
  • - Onboard to CDP Paymaster
  • - Preferred placement in your UI (ie "Create Wallet" button)
|
  1. 1. Migrate your Coinbase SDK to add Base Account to your app, or bump to latest version of any supporting wallet library.
  2. 2. Sign in / up for [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) (takes less than 2 minutes). No KYC needed - just email and phone.
  3. 3. Check out the Paymaster product where the Base Mainnet Paymaster is enabled by default. Set and change your gas policy at any time.
  4. 4. Complete [this form](https://docs.google.com/forms/d/1yPnBFW0bVUNLUN_w3ctCqYM9sjdIQO3Typ53KXlsS5g/viewform?edit_requested=true)
  5. Credits will land within 1 week of completion
| -| 2 | $10k |
  • - Support Base Account
  • - Onboard to CDP Paymaster
|
  1. 1. Migrate your Coinbase SDK to add Base Account to your app, or bump to latest version of any supporting wallet library.
  2. 2. Sign in / up for [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) (takes less than 2 minutes). No KYC needed - just email and phone.
  3. 3. Check out the Paymaster product where the Base Mainnet Paymaster is enabled by default. Set and change your gas policy at any time.
  4. 4. Complete [this form](https://docs.google.com/forms/d/1yPnBFW0bVUNLUN_w3ctCqYM9sjdIQO3Typ53KXlsS5g/viewform?edit_requested=true)
  5. Credits will land within 1 week of completion
| -| Bonus | $1k |
  • - Release demo
| Create a demo of your Coinbase Base Account integration, post on social (Farcaster and/or X) and tag Coinbase Wallet and/or Base | +| 1 | $15k |
  • - Поддержка Base Account
  • - Подключение к CDP Paymaster
  • - Предпочтительное размещение в вашем интерфейсе (например, кнопка "Create Wallet")
|
  1. 1. Мигрируйте Coinbase SDK, чтобы добавить Base Account в ваше приложение, или обновитесь до последней версии любой поддерживающей библиотеки кошельков.
  2. 2. Войдите / зарегистрируйтесь в [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) (занимает менее 2 минут). KYC не требуется - только email и телефон.
  3. 3. Ознакомьтесь с продуктом Paymaster, где Base Mainnet Paymaster включён по умолчанию. Устанавливайте и изменяйте свою газовую политику в любое время.
  4. 4. Заполните [эту форму](https://docs.google.com/forms/d/1yPnBFW0bVUNLUN_w3ctCqYM9sjdIQO3Typ53KXlsS5g/viewform?edit_requested=true)
  5. Кредиты поступят в течение 1 недели после выполнения всех условий
| +| 2 | $10k |
  • - Поддержка Base Account
  • - Подключение к CDP Paymaster
|
  1. 1. MМигрируйте Coinbase SDK, чтобы добавить Base Account в ваше приложение, или обновитесь до последней версии любой поддерживающей библиотеки кошельков.
  2. 2. Войдите / зарегистрируйтесь в [Coinbase Developer Platform](https://www.coinbase.com/developer-platform) (занимает менее 2 минут). KYC не требуется - только email и телефон.
  3. 3. Ознакомьтесь с продуктом Paymaster, где Base Mainnet Paymaster включён по умолчанию. Устанавливайте и изменяйте свою газовую политику в любое время.
  4. 4. Заполните [эту форму](https://docs.google.com/forms/d/1yPnBFW0bVUNLUN_w3ctCqYM9sjdIQO3Typ53KXlsS5g/viewform?edit_requested=true)
  5. Кредиты поступят в течение 1 недели после выполнения всех условий
| +| Бонус | $1k |
  • - Выпуск демо
| Создайте демонстрацию вашей интеграции с Coinbase Base Account, опубликуйте в соцсетях (Farcaster и/или X) и отметьте Coinbase Wallet и/или Base | diff --git a/docs/base-account/more/telemetry.mdx b/docs/base-account/more/telemetry.mdx index 5dd3b0be..810ab998 100644 --- a/docs/base-account/more/telemetry.mdx +++ b/docs/base-account/more/telemetry.mdx @@ -1,34 +1,34 @@ --- -title: Telemetry · Base Account -sidebarTitle: Telemetry -description: Understanding Base Account's anonymous telemetry system and how to configure it. +title: Телеметрия · Base Account +sidebarTitle: Телеметрия +description: Об анонимной системе телеметрии Base Account и о том, как её настроить. --- -Base Account includes an anonymous telemetry system to help us better understand how Base Account is used across applications and improve the developer experience. Participation in this anonymous program is optional—if you'd prefer not to share any usage data, you can easily opt out. +Base Account включает анонимную систему телеметрии, чтобы помочь нам лучше понять, как Base Account используется в различных приложениях, и улучшить опыт разработчиков. Участие в этой анонимной программе необязательно - если вы предпочитаете не делиться данными об использовании, вы можете легко отказаться. -### Why Are We Collecting Telemetry? +### Зачем мы собираем телеметрию? -Base Account provides critical wallet infrastructure for onchain applications with features like signing transactions & messages, signer management, and more. By collecting telemetry data, we can: +Base Account предоставляет критическую инфраструктуру кошелька для ончейн-приложений с такими функциями, как подписание транзакций и сообщений, управление подписантами и другие. Собирая данные телеметрии, мы можем: -- **Monitor Wallet Operation Success**: Track which wallet operations (signing, connecting, transactions) are most reliable and identify failure patterns -- **Data-Informed Improvements**: Help our engineering team generate insights that drive future wallet enhancements and reliability improvements -- **Proactive Issue Detection**: Quickly detect issues with new SDK releases or wallet operations through operational metrics and error monitoring +- **Мониторить успешность операций кошелька**: Отслеживать, какие операции кошелька (подписание, подключение, транзакции) наиболее надёжны, и выявлять паттерны сбоев +- **Улучшения на основе данных**: Помогать нашей инженерной команде получать инсайты, которые стимулируют будущие улучшения и повышение надёжности кошелька +- **Проактивное обнаружение проблем**: Быстро выявлять проблемы с новыми версиями SDK или операциями кошелька через операционные метрики и мониторинг ошибок -### What Data Will Be Collected? +### Какие данные собираются? -Telemetry data is completely anonymous and focused on functional metrics. Specifically, we collect: +Данные телеметрии полностью анонимны и сосредоточены на функциональных метриках. В частности, мы собираем: -- **Request Success Metrics**: Information about the success and failure rates of wallet requests to identify reliability issues -- **Error Events**: Generic error events with operational context to help us improve Base Account reliability -- **UI Component Usage**: Anonymous metrics on interface component functionality to ensure optimal reliability +- **Метрики успешности запросов**: Информацию о показателях успешности и сбоев запросов к кошельку для выявления проблем с надёжностью +- **События ошибок**: Общие события ошибок с операционным контекстом, чтобы помочь нам повысить надёжность Base Account +- **Использование UI-компонентов**: Анонимные метрики функциональности компонентов интерфейса для обеспечения оптимальной надёжности -**Privacy First**: No sensitive data—such as private keys, transaction contents, user addresses, or personal information—is ever collected. +**Конфиденциальность прежде всего**: Никакие конфиденциальные данные - такие как приватные ключи, содержимое транзакций, адреса пользователей или личная информация - никогда не собираются. -### How Does It Work? +### Как это работает? -Telemetry is integrated into the Base Account SDK and automatically triggers when certain wallet events occur (provided telemetry is enabled in your configuration). The data is sent to secure Coinbase endpoints for analysis. +Телеметрия интегрирована в Base Account SDK и автоматически активируется при возникновении определённых событий кошелька (при условии, что телеметрия включена в вашей конфигурации). Данные отправляются на защищённые конечные точки Coinbase для анализа. -For example, when a wallet request occurs, a telemetry event like this is sent: +Например, при выполнении запроса к кошельку отправляется событие телеметрии, подобное этому: ```bash curl 'https://cca-lite.coinbase.com/amp' \ @@ -37,18 +37,18 @@ curl 'https://cca-lite.coinbase.com/amp' \ --data-raw 'e=[{"event_type":"scw_signer.request.started","event_properties":{"method":"eth_requestAccounts","correlationId":"abc123-def456","sdkVersion":"4.3.2","appName":"Your App Name","appOrigin":"https://your-app.com"}}]' ``` -The payload contains an array of telemetry events with operational data including: +Полезная нагрузка содержит массив событий телеметрии с операционными данными, включая: -- **event_type**: The specific wallet operation being tracked -- **method**: The wallet method being called (e.g., `eth_requestAccounts`) -- **correlationId**: A unique identifier for request tracking -- **sdkVersion**: The Base Account SDK version -- **appName**: Your application name -- **appOrigin**: Your application's domain +- **event_type**: Конкретная операция кошелька, которая отслеживается +- **method**: Вызываемый метод кошелька (например, `eth_requestAccounts`) +- **correlationId**: Уникальный идентификатор для отслеживания запросов +- **sdkVersion**: Версия Base Account SDK +- **appName**: Название вашего приложения +- **appOrigin**: Домен вашего приложения -### How Do I Opt Out? +### Как отказаться? -By default, telemetry collection follows an opt-out model. If you'd like to disable telemetry in your app that uses the Base Account SDK, you can configure it during SDK initialization: +По умолчанию сбор телеметрии следует модели отказа. Если вы хотите отключить телеметрию в своём приложении, использующем Base Account SDK, вы можете настроить это во время инициализации SDK: ```typescript import { createCoinbaseWalletSDK } from "@coinbase/wallet-sdk"; @@ -62,7 +62,7 @@ const sdk = createCoinbaseWalletSDK({ const provider = sdk.getProvider(); ``` -For legacy Coinbase Wallet SDK class based components: +Для устаревших компонентов на основе класса Coinbase Wallet SDK: ```tsx import { CoinbaseWalletSDK } from "@coinbase/wallet-sdk"; @@ -77,9 +77,9 @@ const provider = sdk.getProvider({ }); ``` -We believe that this telemetry initiative will help us make Base Account even better for all developers—by focusing our improvements on the most critical wallet operations and catching issues early. If you have any questions or feedback, please reach out to the Base Account team. +Мы считаем, что эта инициатива по телеметрии поможет нам сделать Base Account ещё лучше для всех разработчиков - сосредоточив наши улучшения на наиболее критичных операциях кошелька и выявляя проблемы на раннем этапе. Если у вас есть вопросы или отзывы, пожалуйста, свяжитесь с командой Base Account. -Happy building with Base Account! +Удачной разработки с Base Account! -— The Base Account team +— Команда Base Account diff --git a/docs/base-account/more/troubleshooting/usage-details/gas-usage.mdx b/docs/base-account/more/troubleshooting/usage-details/gas-usage.mdx index 89bc88b2..c8bee02d 100644 --- a/docs/base-account/more/troubleshooting/usage-details/gas-usage.mdx +++ b/docs/base-account/more/troubleshooting/usage-details/gas-usage.mdx @@ -1,21 +1,21 @@ --- -title: "Gas Usage" +title: "Использование газа" --- -Base Accounts use more gas for transactions than traditional Ethereum accounts. On L2 networks, the cost difference to the user is a matter of cents. -The gas difference is due to the additional overhead required for: +Base Accounts используют больше газа для транзакций, чем традиционные Ethereum-аккаунты. В сетях L2 разница в стоимости для пользователя составляет копейки. +Разница в газе обусловлена дополнительными накладными расходами, необходимыми для: -1. **ERC-4337 Bundling** -2. **Smart Contract Operations**, including one time deployment of the Base Account contract -3. **Signature Verification** +1. **Объединения (Bundling) ERC-4337** +2. **Операций со смарт-контрактами**, включая разовое развёртывание контракта Base Account +3. **Верификации подписей** -## Gas Usage Breakdown +## Детализация использования газа -Here's a rough comparison of gas usage per account: +Вот примерное сравнение использования газа на аккаунт: -| Operation Type | Traditional Ethereum Account | Base Account | +| Тип операции | Традиционный Ethereum-аккаунт | Base Account | |---------------|------------|--------------| -| Native Token Transfer | ~21,000 gas | ~100,000 gas | -| ERC-20 Token Transfer | ~65,000 gas | ~150,000 gas | -| First Deployment | N/A | ~300,000+ gas | +| Перевод нативного токена | ~21,000 gas | ~100,000 gas | +| Перевод токена ERC-20 | ~65,000 gas | ~150,000 gas | +| Первое развёртывание | N/A | ~300,000+ gas | diff --git a/docs/base-account/more/troubleshooting/usage-details/popups.mdx b/docs/base-account/more/troubleshooting/usage-details/popups.mdx index bccea302..739a0a26 100644 --- a/docs/base-account/more/troubleshooting/usage-details/popups.mdx +++ b/docs/base-account/more/troubleshooting/usage-details/popups.mdx @@ -1,37 +1,37 @@ --- -title: "Popup Tips" +title: "Подсказки по всплывающим окнам" --- -## Overview -When a Base Account is connected and Coinbase Wallet SDK receives a request, it opens -[keys.coinbase.com](https://keys.coinbase.com/) in a popup window and passes the request to the popup for handling. -Keep the following points in mind when working with the Base Account popup. +## Обзор +Когда подключён Base Account и Coinbase Wallet SDK получает запрос, он открывает +[keys.coinbase.com](https://keys.coinbase.com/) во всплывающем окне и передаёт запрос туда для обработки. +Учитывайте следующие моменты при работе со всплывающим окном Base Account. -## Default blocking behavior -- Most modern browsers block all popups by default, unless they are triggered by a click. -- If a popup is blocked the browser shows a notification to the user, allowing them to manage popup settings. +## Поведение блокировки по умолчанию +- Большинство современных браузеров блокирует все всплывающие окна по умолчанию, если они не вызваны кликом. +- Если всплывающее окно заблокировано, браузер показывает уведомление пользователю, позволяя ему управлять настройками всплывающих окон. -### What to do about it -- Ensure there is no additional logic between the button click and the request to open the Base Account popup, -as browsers might perceive the request as programmatically initiated. -- If logic is unavoidable, keep it minimal and test thoroughly in all supported browsers. +### Что с этим делать +- Убедитесь, что между кликом по кнопке и запросом на открытие всплывающего окна Base Account нет дополнительной логики, +так как браузеры могут воспринимать запрос как программно инициированный. +- Если логику нельзя избежать, делайте её минимальной и тщательно тестируйте во всех поддерживаемых браузерах. ## `Cross-Origin-Opener-Policy` -If the Base Account popup opens and displays an error or infinite spinner, it may be due to the dapp's `Cross-Origin-Opener-Policy`. Be sure to use a directive that allows the Base Account popup to function. +Если всплывающее окно Base Account открывается и отображает ошибку или бесконечный спиннер, это может быть связано с `Cross-Origin-Opener-Policy` вашего приложения. Убедитесь, что используется директива, позволяющая всплывающему окну Base Account функционировать. -- ✅ Allows Base Account popup to function - - `unsafe-none` (default) - - `same-origin-allow-popups` (recommended) -- ❌ Breaks Base Account popup +- ✅ Позволяет всплывающему окну Base Account работать + - `unsafe-none` (по умолчанию) + - `same-origin-allow-popups` (рекомендуется) +- ❌ Ломает всплывающее окно Base Account - `same-origin` -For more detailed information refer to the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy). +Для получения более подробной информации обратитесь к [документации MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy). -## Base Account popup 'linger' behavior -- Sometimes a dapp may programmatically make a followup request based on the response to a previous request. -Normally, browsers block these programmatic requests to open popups. -- To address this, after the Base Account popup responds to a request, it will linger for 200ms to listen for another incoming request before closing. - - If a request is received *during* this 200ms window, it will be received and handled within the same popup window. - - If a request is received *after* the 200ms window and the popup has closed, opening the Base Account popup will be blocked by the browser. +## Поведение "задержки" всплывающего окна Base Account +- Иногда dapp может программно выполнить последующий запрос на основе ответа на предыдущий запрос. +Обычно браузеры блокируют такие программные запросы на открытие всплывающих окон. +- Чтобы решить эту проблему, после ответа на запрос всплывающее окно Base Account задерживается на 200мс, чтобы прослушивать входящие запросы перед закрытием. + - Если запрос получен в течение этого 200мс окна, он будет принят и обработан в том же всплывающем окне. + - Если запрос получен после 200мс окна и всплывающее окно закрылось, открытие всплывающего окна Base Account будет заблокировано браузером. diff --git a/docs/base-account/more/troubleshooting/usage-details/simulations.mdx b/docs/base-account/more/troubleshooting/usage-details/simulations.mdx index 0c5b4829..09b1202e 100644 --- a/docs/base-account/more/troubleshooting/usage-details/simulations.mdx +++ b/docs/base-account/more/troubleshooting/usage-details/simulations.mdx @@ -1,16 +1,16 @@ --- -title: "Transaction Simulation Data" +title: "Данные симуляции транзакции" --- -There is a hidden feature which enables you to easily copy transaction simulation request and response data which can then be pasted it in a text editor to inspect. +Существует скрытая функция, которая позволяет легко скопировать данные запроса и ответа симуляции транзакции, чтобы затем вставить их в текстовый редактор для изучения. -## Instructions -- Click the area defined in red **_five times_**, then paste the copied data in a text editor. +## Инструкции +- Нажмите на область, выделенную красным **пять раз**, затем вставьте скопированные данные в текстовый редактор.
- ![Copy transaction simulation data click zone](/images/smart-wallet/copyTxnSimClickZone.png) + ![Зона нажатия для копирования данных симуляции транзакции](/images/smart-wallet/copyTxnSimClickZone.png)
diff --git a/docs/base-account/more/troubleshooting/usage-details/unsupported-calls.mdx b/docs/base-account/more/troubleshooting/usage-details/unsupported-calls.mdx index 0a55f501..e1aa5c87 100644 --- a/docs/base-account/more/troubleshooting/usage-details/unsupported-calls.mdx +++ b/docs/base-account/more/troubleshooting/usage-details/unsupported-calls.mdx @@ -1,43 +1,43 @@ --- -title: 'Unsupported Calls' +title: 'Неподдерживаемые вызовы' --- -Base Account implements an Ethereum Provider JavaScript API (as detailed in [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193)) -and follows the [ERC-4337](https://eips.ethereum.org/EIPS/eip-4337) standard for account abstraction. +Base Account реализует JavaScript API Ethereum Provider (как описано в [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193)) +и следует стандарту [ERC-4337](https://eips.ethereum.org/EIPS/eip-4337) для абстракции аккаунтов. -This means that apps interacting with Base Account can expect it to behave like a regular Ethereum Virtual Machine (EVM) account. -However, there are some calls that are not supported by Base Accounts for incompatibility or security reasons. -This is a list of calls that are not supported: +Это означает, что приложения, взаимодействующие с Base Account, могут ожидать, что он ведёт себя как обычный аккаунт Ethereum Virtual Machine (EVM). +Однако есть некоторые вызовы, которые не поддерживаются Base Accounts по причинам несовместимости или безопасности. +Вот список неподдерживаемых вызовов: -- [Self Calls](#self-calls): This refers to the ability of an app to use the user's account to call itself. -- [CREATE](#create): This refers to the ability of an app to create a new contract using the OPCODE `CREATE`. +- [Вызовы к самому себе (Self Calls)](#self-calls): Способность приложения использовать аккаунт пользователя для вызова самого себя. +- [CREATE](#create): Способность приложения создавать новый контракт с использованием OPCODE `CREATE`. -## Self Calls +## Вызовы к самому себе (Self Calls) -For security reasons, we do not allow 3rd party apps to make calls to a user's own Base Account address. -This could allow apps to change owners, upgrade the user's account, or cause other issues. +По соображениям безопасности мы не позволяем сторонним приложениям совершать вызовы к адресу Base Account самого пользователя. +Это может позволить приложениям изменять владельцев, обновлять аккаунт пользователя или вызывать другие проблемы. ## CREATE -This is a limitation of the ERC-4337 standard and smart accounts. -Currently, we do not support the `CREATE` opcode for smart contracts deployment. -Future versions of Base Account may support it. +Это ограничение стандарта ERC-4337 и смарт-аккаунтов. +В настоящее время мы не поддерживаем OPCODE `CREATE` для развёртывания смарт-контрактов. +Будущие версии Base Account могут поддерживать его. -You can use a factory contract or a transaction with the `CREATE2` opcode to deploy a smart contract. +Вы можете использовать фабричный контракт или транзакцию с opcode `CREATE2` для развёртывания смарт-контракта. -## Solidity's Builtin `transfer` function +## Встроенная функция Solidity `transfer` -The `transfer` function is a built-in member of the `address` type in Solidity that can be used to send ETH to an address. Base Account wallets cannot receive ETH using this function. -This function has long been considered deprecated in favor of `call` by the Solidity community, but some older contracts still use it. +Функция `transfer` - это встроенный член типа `address` в Solidity, который можно использовать для отправки ETH на адрес. Кошельки Base Account не могут получать ETH с использованием этой функции. +Этот метод уже давно считается устаревшим в пользу call в сообществе Solidity, но некоторые старые контракты всё ещё используют его. -The reason for this is that `transfer` only forwards 2300 gas to the `transfer` call, a protective mechanism that was designed to prevent reentrancy attacks by limiting the amount of -gas available to a smart contract that might reenter the caller. -In the modern world of smart contract wallets (including for Base Account), this is often not enough gas for the smart contract's `receive` or `fallback` functions to complete their work, -causing the transaction to revert. +Причина в том, что transfer передаёт только 2300 газа в вызов `transfer`, что является защитным механизмом, разработанным для предотвращения атак повторного входа путём ограничения количества +газа, доступного смарт-контракту, который может повторно войти в вызывающую сторону. +В современном мире смарт-контрактных кошельков (включая Base Account) этого часто недостаточно для завершения работы функций `receive` или `fallback` смарт-контракта, +что приводит к откату транзакции. -### Known affected contracts +### Известные затронутые контракты -- The [WETH9 contract](https://basescan.org/token/0x4200000000000000000000000000000000000006) uses `transfer` to send ETH to the user's wallet and therefore Base Accounts cannot directly unwrap ETH from it. +- Контракт [WETH9](https://basescan.org/token/0x4200000000000000000000000000000000000006) использует `transfer` для отправки ETH на кошелёк пользователя, поэтому Base Accounts не могут напрямую разворачивать ETH из него. diff --git a/docs/base-account/more/troubleshooting/usage-details/wallet-library-support.mdx b/docs/base-account/more/troubleshooting/usage-details/wallet-library-support.mdx index 3db0359b..6f0e44ac 100644 --- a/docs/base-account/more/troubleshooting/usage-details/wallet-library-support.mdx +++ b/docs/base-account/more/troubleshooting/usage-details/wallet-library-support.mdx @@ -1,11 +1,11 @@ --- -title: "Wallet Library Support" +title: "Поддержка библиотек кошельков" --- -Below are some popular wallet libraries and what we know of their plans for day 1 support for Base Account. +Ниже приведены некоторые популярные библиотеки кошельков и информация об их планах по поддержке Base Account с первого дня. -| Name | Support | +| Название | Поддержка | | ---------------------------------------------------------------------------------- | ------- | | [Dynamic](https://docs.dynamic.xyz/wallets/advanced-wallets/coinbase-smart-wallet) | ✅ | | [Privy](https://docs.privy.io/guide/react/recipes/misc/coinbase-smart-wallets) | ✅ | diff --git a/docs/base-account/overview/what-is-base-account.mdx b/docs/base-account/overview/what-is-base-account.mdx index 7ae0197e..245cc7c8 100644 --- a/docs/base-account/overview/what-is-base-account.mdx +++ b/docs/base-account/overview/what-is-base-account.mdx @@ -1,40 +1,40 @@ --- -title: "Base Account Overview" -description: "What is a Base Account and how the Base Account SDK lets you add universal sign-in and one-tap USDC payments to any app." +title: "Обзор Base Account" +description: "Что такое Base Account и как Base Account SDK позволяет добавить универсальный вход и платежи USDC в одно нажатие в любое приложение." --- -> **TL;DR** – Base Accounts are the onchain identity and account layer powering the [Base App](https://base.app). With the **Base Account SDK** you can connect to over one hundred thousand users and unlock authentication and payments with just a few lines of code. +> **TL;DR** – Base Accounts - это уровень ончейн-идентификации и аккаунтов, который питает [Base App](https://base.app). С **Base Account SDK** вы можете подключиться к более чем ста тысячам пользователей и разблокировать аутентификацию и платежи всего несколькими строками кода. -## What is a Base Account? +## Что такое Base Account? -A Base Account is a Smart-Wallet–backed account that gives every user: +Base Account - это аккаунт на основе смарт-кошелька, который дает каждому пользователю: -* **Universal sign-on** – one passkey works across every Base-enabled app. -* **One-tap payments** – low-friction USDC payments built into the account layer. -* **Private profile vault** – opt-in sharing of email, phone, shipping address, and more. -* **Multi-chain support** – one address that works across nine EVM networks (and counting). +* **Универсальный вход** – один пасскей работает во всех приложениях с поддержкой Base. +* **Платежи в одно нажатие** – беспрепятственные платежи USDC, встроенные в уровень аккаунта. +* **Приватное хранилище профиля** – опциональный обмен email, телефоном, адресом доставки и другим. +* **Поддержка мультичейн** – один адрес, который работает в девяти EVM-сетях (и их количество растет). -> Under the hood, each Base Account is an ERC-4337 Smart Wallet that can be deployed on any EVM-compatible chain; nine EVM mainnet chains are enabled out of the box, including Base Mainnet. +> Под капотом каждый Base Account - это ERC-4337 умный кошелек, который может быть развернут в любой EVM-совместимой цепи; девять основных EVM-сетей включены из коробки, включая Base Mainnet. -**Supported networks** +**Поддерживаемые сети** -- **Mainnet:** Base • Arbitrum • Optimism • Zora • Polygon • BNB • Avalanche • Lordchain • Ethereum Mainnet (not recommended due to costs) +- **Mainnet:** Base • Arbitrum • Optimism • Zora • Polygon • BNB • Avalanche • Lordchain • Ethereum Mainnet (не рекомендуется из-за стоимости) - **Testnet:** Sepolia • Base Sepolia -## Why should developers care? +## Почему это важно для разработчиков? -* **Higher conversion** – no app installs, seed phrases, or network switches. -* **Fewer drop-offs at checkout** – a single `pay()` call handles gas and settlement. -* **Cross-app identity** – fetch a verified email or shipping address via the same SDK. -* **Self-custodial** – users hold the keys; you never touch private data or funds. +* **Более высокая конверсия** – никаких установок приложений, сид-фраз или переключения сетей. +* **Меньше отказов при оплате** – один вызов `pay()` обрабатывает газ и расчеты. +* **Кросс-приложенная идентичность** – получайте проверенный email или адрес доставки через тот же SDK. +* **Самокастодиальный** – пользователи хранят ключи; вы никогда не касаетесь приватных данных или средств. -## Next steps +## Следующие шаги -| Goal | Start here | +| Цель | Начните здесь | | --- | --- | -| Build & run in 5 min | [Quickstart](/base-account/quickstart/web) | -| Authentication flow | [Authenticate users](/base-account/guides/authenticate-users) | -| Accept USDC payments on Base | [Accept payments](/base-account/guides/accept-payments) | -| Deep-dive API shapes | [TypeScript API reference](/base-account/reference/core/getProvider) | +| Собрать и запустить за 5 мин | [Быстрый старт](/base-account/quickstart/web) | +| Процесс аутентификации | [Аутентификация пользователей](/base-account/guides/authenticate-users) | +| Прием платежей USDC в Base | [Прием платежей](/base-account/guides/accept-payments) | +| Глубокое погружение в API | [Справочник TypeScript API](/base-account/reference/core/getProvider) | diff --git a/docs/base-account/quickstart/ai-tools-available-for-devs.mdx b/docs/base-account/quickstart/ai-tools-available-for-devs.mdx index d1da792e..a8c98899 100644 --- a/docs/base-account/quickstart/ai-tools-available-for-devs.mdx +++ b/docs/base-account/quickstart/ai-tools-available-for-devs.mdx @@ -1,10 +1,10 @@ --- -title: "AI Tools for Base Account Developers" +title: "Инструменты AI для разработчиков Base Account" --- -Base Account has a number of AI tools available for builders and developers. -We keep expanding the list of tools and features, so please check back soon for updates. +Base Account предлагает ряд инструментов искусственного интеллекта для разработчиков и специалистов. +Мы постоянно расширяем список инструментов и функций, поэтому следите за обновлениями. - This doc is updated for Mobile Wallet Protocol Client `v1.0.0` + Эта документация обновлена для Клиента Мобильного Протокола Кошелька версии `v1.0.0` - **Deep Link Handling** + **Обработка глубоких ссылок** - Breaking change in v1.0.0: Universal Links and App Links requirements are - removed in favor of custom schemes (e.g. `myapp://`). + Критическое изменение в v1.0.0: требования к Universal Links и App Links удалены в пользу + пользовательских схем (custom schemes), например `myapp://`. -## Before You Start +## Перед началом работы -This guide walks you through adding support for Base Account into an existing React Native app or starter project. +Это руководство проведет вас через процесс добавления поддержки Base Account в существующее приложение React Native или стартовый проект. -If you prefer to skip ahead and start with a working example, navigate to the repository below: +Если вы хотите сразу перейти к рабочему примеру, перейдите в репозиторий ниже: - + -If you are looking to integrate Base Account into an existing React Native app or starter project, follow the instructions below. +Если вы хотите интегрировать Base Account в существующее приложение React Native или стартовый проект, следуйте приведенным ниже инструкциям. -## Step 1: Install Mobile Wallet Protocol Client +## Шаг 1: Установите Клиент Мобильного Протокола Кошелька -Add the latest version of [Mobile Wallet Protocol Client](https://mobilewalletprotocol.github.io/wallet-mobile-sdk/) to your project. +Добавьте последнюю версию [Клиента Мобильного Протокола Кошелька](https://mobilewalletprotocol.github.io/wallet-mobile-sdk/) в ваш проект. ```zsh npm @@ -45,12 +44,12 @@ yarn add @mobile-wallet-protocol/client@latest ``` -## Step 2: Add Polyfills +## Шаг 2: Добавьте полифиллы -### Install peer dependencies +### Установите peer-зависимости -The Mobile Wallet Protocol Client library requires the [Expo WebBrowser](https://docs.expo.dev/versions/latest/sdk/webbrowser/) and [Async Storage](https://react-native-async-storage.github.io/async-storage/docs/install) packages to be installed. -Follow the instructions on the respective pages for any additional setup. +Библиотеке Клиента Мобильного Протокола Кошелька требуются установленные пакеты [Expo WebBrowser](https://docs.expo.dev/versions/latest/sdk/webbrowser/) и [Async Storage](https://react-native-async-storage.github.io/async-storage/docs/install). +Следуйте инструкциям на соответствующих страницах для любой дополнительной настройки. ```zsh npm @@ -62,11 +61,11 @@ yarn add expo expo-web-browser @react-native-async-storage/async-storage ``` -### Polyfills +### Полифиллы -Mobile Wallet Protocol Client requires `crypto.randomUUID`, `crypto.getRandomValues`, and `URL` to be polyfilled globally since they are not available in the React Native environment. +Клиенту Мобильного Протокола Кошелька требуются глобально доступные полифиллы для `crypto.randomUUID`, `crypto.getRandomValues` и `URL`, так как они недоступны в среде React Native. -Below is an example of how to polyfill these functions in your app using the [expo-crypto](https://docs.expo.dev/versions/latest/sdk/crypto/) and [expo-standard-web-crypto](https://github.com/expo/expo/tree/master/packages/expo-standard-web-crypto/) packages. +Ниже приведен пример, как добавить полифиллы для этих функций в ваше приложение с помощью пакетов [expo-crypto](https://docs.expo.dev/versions/latest/sdk/crypto/) и [expo-standard-web-crypto](https://github.com/expo/expo/tree/master/packages/expo-standard-web-crypto/). ```zsh npm @@ -97,30 +96,30 @@ import { CoinbaseWalletSDK } from "@mobile-wallet-protocol/client"; ``` -## Step 3: Usage +## Шаг 3: Использование -Mobile Wallet Protocol Client provides 2 interfaces for mobile app to interact with the Base Account, an EIP-1193 compliant provider interface and a wagmi connector. +Клиент Мобильного Протокола Кошелька предоставляет 2 интерфейса для взаимодействия мобильного приложения с Base Account: интерфейс провайдера, совместимый со стандартом EIP-1193, и коннектор для wagmi. - If your app is using wallet aggregator, go straight to [**Option 2: Wagmi - Connector**](#option-2-wagmi-connector) for 1-line integration. + Если ваше приложение использует агрегатор кошельков, переходите сразу к + [**Варианту 2: Коннектор Wagmi**](#option-2-wagmi-connector) для интеграции в одну строку. -### Option 1: EIP-1193 Provider +### Вариант 1: Провайдер EIP-1193 - The `app` prefix in SDK config params is removed in v1.0.0. + Префикс `app` в параметрах конфигурации SDK удален в версии `v1.0.0`. -Create a new `EIP1193Provider` instance, which is EIP-1193 compliant. +Создайте новый экземпляр `EIP1193Provider`, который совместим со стандартом EIP-1193. ```tsx App.tsx import { EIP1193Provider } from "@mobile-wallet-protocol/client"; -// Step 1. Initialize provider with your dapp's metadata and target wallet +// Шаг 1. Инициализируйте провайдер с метаданными вашего dapp и целевым кошельком const metadata = { name: "My App Name", - customScheme: "myapp://", // only custom scheme (e.g. `myapp://`) is supported in v1.0.0 + customScheme: "myapp://", // в v1.0.0 поддерживаются только пользовательские схемы (например `myapp://`) chainIds: [8453], logoUrl: "https://example.com/logo.png", }; @@ -131,7 +130,7 @@ const provider = new EIP1193Provider({ // ... -// 2. Use the provider +// 2. Используйте провайдер const addresses = await provider.request({ method: "eth_requestAccounts" }); const signedData = await provider.request({ method: "personal_sign", @@ -139,9 +138,9 @@ const signedData = await provider.request({ }); ``` -### Option 2: Wagmi Connector +### Вариант 2: Коннектор Wagmi -Add the latest version of Mobile Wallet Protocol wagmi-connectors to your project. +Добавьте последнюю версию коннекторов Mobile Wallet Protocol для wagmi в ваш проект. ```zsh npm @@ -153,7 +152,7 @@ yarn add @mobile-wallet-protocol/wagmi-connectors@latest ``` -Simply import the `createConnectorFromWallet` function and pass in the wallet you want to use to wagmi config. +Просто импортируйте функцию `createConnectorFromWallet` и передайте ей нужный кошелек в конфигурацию wagmi. ```ts config.ts import { @@ -163,7 +162,7 @@ import { const metadata = { name: "My App Name", - customScheme: "myapp://", // only custom scheme (e.g. `myapp://`) is supported in v1.0.0 + customScheme: "myapp://", // в v1.0.0 поддерживаются только пользовательские схемы (например `myapp://`) chainIds: [8453], logoUrl: "https://example.com/logo.png", }; @@ -182,7 +181,7 @@ export const config = createConfig({ }); ``` -Then you can use wagmi's react interface to interact with the Base Account. +Затем вы можете использовать React-интерфейс wagmi для взаимодействия с Base Account. ```tsx App.tsx import { useConnect } from "wagmi"; @@ -201,7 +200,7 @@ return ( ); ``` -## Give feedback! +## Поделитесь отзывом! -Send us feedback on the [Base Discord](https://discord.com/invite/buildonbase/) or create a new issue on the [MobileWalletProtocol/react-native-client](https://github.com/MobileWalletProtocol/react-native-client/issues) repository. +Отправьте нам отзыв в [дискорд Base](https://discord.com/invite/buildonbase/) или создайте новую проблему (issue) в репозитории [MobileWalletProtocol/react-native-client](https://github.com/MobileWalletProtocol/react-native-client/issues). diff --git a/docs/base-account/quickstart/web-react.mdx b/docs/base-account/quickstart/web-react.mdx index 4e90f4a5..3b3456dc 100644 --- a/docs/base-account/quickstart/web-react.mdx +++ b/docs/base-account/quickstart/web-react.mdx @@ -1,15 +1,15 @@ --- title: "Web (Next.js)" -description: "Quickly add Sign in with Base and Base Pay to any Next.js app" +description: "Быстро добавьте Sign in with Base и Base Pay в любое приложение Next.js" --- import { GithubRepoCard } from "/snippets/GithubRepoCard.mdx" -This quick-start shows the **minimum** code required to add Sign in with Base (SIWB) and Base Pay to any Next.js app using the Base Account SDK. +Этот быстрый старт показывает минимальный код, необходимый для добавления Sign in with Base (SIWB) и Base Pay в любое приложение Next.js с использованием Base Account SDK. -## 1. Create a new Next.js app +## 1. Создайте новое приложение Next.js -If you're starting fresh, create a new Next.js app: +Если вы начинаете с нуля, создайте новое приложение Next.js: ```bash npm @@ -33,9 +33,9 @@ cd base-account-quickstart ``` -When prompted during setup, you can choose the default options or customize as needed. For this quickstart, the default settings work perfectly. +При настройке вы можете выбрать стандартные параметры или изменить их по необходимости. Для этого быстрого старта стандартные настройки подходят идеально. -## 2. Install the SDK +## 2. Установите SDK ```bash npm @@ -56,14 +56,14 @@ bun add @base-org/account @base-org/account-ui -**Got a peer dependency error?** +**Получили ошибку о peer dependency?** -Use `--legacy-peer-deps` flag if you get a peer dependency error. +Используйте флаг `--legacy-peer-deps`, если получили ошибку о peer dependency. -## 3. Create the main component +## 3. Создайте основной компонент -Replace the contents of `app/page.tsx` (or `app/page.js` if not using TypeScript) with this component: +Замените содержимое `app/page.tsx` (или `app/page.js`, если не используете TypeScript) этим компонентом: ```jsx title="app/page.tsx" lineNumbers 'use client'; @@ -78,7 +78,7 @@ export default function Home() { const [paymentId, setPaymentId] = useState(''); const [theme, setTheme] = useState('light'); - // Initialize SDK + // Инициализируем SDK const sdk = createBaseAccountSDK( { appName: 'Base Account Quick-start', @@ -86,7 +86,7 @@ export default function Home() { } ); - // Optional sign-in step – not required for `pay()`, but useful to get the user address + // Опциональный шаг входа – не требуется для `pay()`, но полезен для получения адреса пользователя const handleSignIn = async () => { try { await sdk.getProvider().request({ method: 'wallet_connect' }); @@ -96,13 +96,13 @@ export default function Home() { } }; - // One-tap USDC payment using the pay() function + // Платеж USDC в одно нажатие с использованием функции `pay()` const handlePayment = async () => { try { const { id } = await pay({ - amount: '0.01', // USD – SDK quotes equivalent USDC - to: '0xRecipientAddress', // Replace with your recipient address - testnet: true // set to false or omit for Mainnet + amount: '0.01', // USD – SDK конвертирует в эквивалент USDC + to: '0xRecipientAddress', // Замените на адрес получателя + testnet: true // установите false или опустите для Mainnet }); setPaymentId(id); @@ -113,7 +113,7 @@ export default function Home() { } }; - // Check payment status using stored payment ID + // Проверка статуса платежа с использованием сохраненного ID платежа const handleCheckStatus = async () => { if (!paymentId) { setPaymentStatus('No payment ID found. Please make a payment first.'); @@ -205,37 +205,37 @@ export default function Home() { ``` -**Note:** +**Примечание:** -Make sure to replace `0xRecipientAddress` with your recipient address. +Убедитесь, что заменили `0xRecipientAddress` на адрес вашего получателя. -**Base Pay and SIWB are independent** +**Base Pay и SIWB работают независимо** -You DO NOT need to use SIWB to use Base Pay. You can just call the `pay()` function without any additional setup. +Вам НЕ нужно использовать Sign in with Base (SIWB) для работы с Base Pay. Вы можете просто вызвать функцию `pay()` без какой-либо дополнительной настройки. -## 4. Start your app +## 4. Запустите ваше приложение ```bash npm run dev ``` -Open http://localhost:3000, click **Sign in with Base** (optional) and then **Pay**, approve the transaction, and you've sent 5 USDC on Base Sepolia—done! 🎉 +Откройте http://localhost:3000, нажмите **Sign in with Base** (опционально) а затем **Pay**, подтвердите транзакцию, и вы отправили 5 USDC в сети Base Sepolia — готово! 🎉 -**Note:** If you have an existing Next.js app, just install the SDK (`npm install @base-org/account @base-org/account-ui`) and add the component above to your project. For other React frameworks, you can adapt this component as needed. +**Примечание:** Если у вас уже есть приложение на Next.js, просто установите SDK (`npm install @base-org/account @base-org/account-ui`) и добавьте приведенный выше компонент в ваш проект. Для других React-фреймворков вы можете адаптировать этот компонент по необходимости. -## Next steps +## Следующие шаги -* **[Authenticate Users](/base-account/guides/authenticate-users)** - strong authentication by setting up Sign in with Base with backend verification -* **[Accept Payments](/base-account/guides/accept-payments)** explore all the features of Base Pay -* **[Sign in with Base Button](/base-account/reference/ui-elements/sign-in-with-base-button)** – use the Sign in with Base Button component to quickly add authentication to your app -* **[Base Pay Button](/base-account/reference/ui-elements/base-pay-button)** – use the Base Pay Button component to quickly add payments to your app +* **[Аутентификация пользователей](/base-account/guides/authenticate-users)** - настройка надежной аутентификации с помощью Sign in with Base и проверкой на стороне сервера +* **[Прием платежей](/base-account/guides/accept-payments)** изучите все возможности Base Pay +* **[Кнопка Sign in with Base](/base-account/reference/ui-elements/sign-in-with-base-button)** – используйте компонент кнопки для быстрого добавления аутентификации в ваше приложение +* **[Кнопка Base Pay](/base-account/reference/ui-elements/base-pay-button)** – используйте компонент кнопки для быстрого добавления платежей в ваше приложение -**Please Follow the Brand Guidelines** +**Пожалуйста, следуйте руководству по бренду** -If you intend on using the `SignInWithBaseButton` or `BasePayButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. +Если вы планируете использовать SignInWithBaseButton или BasePayButton, пожалуйста, следуйте [руководству по бренду](/base-account/reference/ui-elements/brand-guidelines) чтобы обеспечить единообразие в вашем приложении. - \ No newline at end of file + diff --git a/docs/base-account/quickstart/web.mdx b/docs/base-account/quickstart/web.mdx index f41b8037..379b1649 100644 --- a/docs/base-account/quickstart/web.mdx +++ b/docs/base-account/quickstart/web.mdx @@ -1,30 +1,30 @@ --- title: "Web (HTML + JS)" -description: "Integrate Sign in with Base and Base Pay using nothing but HTML and JavaScript." +description: "Интегрируйте Sign in with Base и Base Pay, используя только HTML и JavaScript." --- -This quick-start shows the **minimum** code required to add Sign in with Base and Base Pay to any web page using nothing but the Base Account SDK. No frameworks, no additional libraries. +Этот быстрый старт показывает **минимальный** код, необходимый для добавления Sign in with Base и Base Pay на любую веб-страницу, используя только Base Account SDK. Никаких фреймворков, никаких дополнительных библиотек. -## 1. Install the SDK (Optional) +## 1. Установите SDK (Опционально) -**Interactive Playground:** Want to test the SDK functions before integrating? Try our [Base Pay SDK Playground](https://base.github.io/account-sdk/pay-playground) to experiment with `pay()` and `getPaymentStatus()` functions. +**Интерактивная площадка:** Хотите протестировать функции SDK перед интеграцией? Попробуйте нашу [Base Pay SDK Playground](https://base.github.io/account-sdk/pay-playground) чтобы поэкспериментировать с функциями `pay()` и `getPaymentStatus()`. -You can use the Base Account SDK in two ways: +Вы можете использовать Base Account SDK двумя способами: -### Option A: CDN (No installation required) -Just include the script tag in your HTML - no build tools needed! +### Вариант A: CDN (Установка не требуется) +Просто включите тег script в ваш HTML - никаких инструментов сборки не нужно! ```html index.html -[...rest of your code] +[...остальная часть вашего кода] -[...rest of your code] +[...остальная часть вашего кода] ``` -For a full example, see [example](#2-copy-paste-this-html-file) below. +Полный [пример смотрите ниже] (#2-copy-paste-this-html-file). -### Option B: NPM Package -If you prefer to install locally: +### Вариант B: NPM Пакет +Если предпочитаете установить локально: ```bash npm @@ -44,17 +44,17 @@ bun add @base-org/account ``` -Then use ES modules: +Затем используйте ES модули: ```html ``` -This guide uses the CDN approach for simplicity. +Это руководство использует подход CDN для простоты. -## 2. Copy-paste this HTML file +## 2. Скопируйте этот HTML файл ```html title="index.html" lineNumbers @@ -71,11 +71,11 @@ This guide uses the CDN approach for simplicity.
- +