# Introduction

## UseMoon.ai - Your All-in-One DeFi and Blockchain Solution

Welcome to UseMoon.ai, the cutting-edge platform that brings the power of decentralized finance (DeFi) and blockchain technology to your fingertips. Our comprehensive suite of tools and integrations empowers developers, traders, and blockchain enthusiasts to seamlessly interact with various protocols and chains.

### 🚀 Why Choose UseMoon.ai?

* **Comprehensive DeFi Support**: From lending and borrowing to yield farming, we've got you covered.
* **Multi-chain Compatibility**: Interact with numerous blockchains through a single, unified interface.
* **Advanced Features**: Leverage cutting-edge DeFi mechanisms like flash loans and cross-chain swaps.
* **Developer-Friendly**: Robust APIs, documentation, and tools to accelerate your blockchain projects.
* **Security-First Approach**: Built with best practices to ensure the safety of your assets and data.

### 📚 Our Capabilities

#### DeFi Support

**Lending and Borrowing**

* AAVE v3 integration
* Lending pool operations
* Borrowing and repaying assets
* Collateral management
* Flash loans

**Decentralized Exchanges (DEX)**

* Uniswap v2 and v3 support
* Liquidity provision and removal
* Token swapping
* Price quotes and routing
* Odos support

**Yield Farming and Staking**

* VeNFT staking
* Gauge systems (e.g., Lynex, Ramses)
* Reward claiming and distribution

**Cross-chain Operations**

* LiFi integration for cross-chain swaps
* ThorSwap for cross-chain operations

**Leveraging**

* Leverager contract interactions
* Leverage and deleverage operations

#### Blockchain Interactions

**Multi-chain Support**

* Ethereum and EVM-compatible chains
* Bitcoin and Bitcoin Cash
* Solana
* Ripple (XRP)
* Cosmos
* Tron
* Dogecoin
* Litecoin
* EOS

#### Account Management

* Account creation and deletion
* Key management and export
* Balance checking

#### Transaction Handling

* Transaction signing and broadcasting
* Gas estimation and management
* Nonce handling

#### Token Standards

* ERC20: Transfers, allowances, balance checking, metadata retrieval
* ERC721 (NFTs): Transfers, ownership management, metadata retrieval
* ERC1155: Multi-token standard operations, batch transfers
* ERC4626 (Tokenized Vaults): Deposits, withdrawals, share minting and burning

#### Advanced Features

* On-ramp and Off-ramp: Fiat to crypto conversions, various payment methods
* Data and Analytics: Financial datasets, token analytics, price data
* Oracles and Price Feeds: ChainLink integration

#### Governance

* Voting mechanisms
* Proposal creation and execution

#### Utility Functions

* ENS (Ethereum Name Service): Domain resolution, reverse lookup
* Multicall: Batch contract calls, aggregated data retrieval
* Gas Optimization: EIP-1559 support, gas price suggestions

#### Developer Tools

* Simulation and Testing: Transaction simulation, dry runs
* ABI Handling: Encoding and decoding
* Contract Interactions: Generic calls, custom function execution

### 🌟 Unleash the Power of DeFi with UseMoon.ai

UseMoon.ai is your gateway to the decentralized finance universe. Our platform offers:

* **Seamless Integration**: Easily incorporate advanced DeFi functionalities into your projects.
* **Cross-chain Flexibility**: Operate across multiple blockchains without the complexity.
* **Comprehensive Tools**: From basic transfers to complex flash loan strategies, we've got it all.
* **Real-time Data**: Access up-to-date analytics and price feeds for informed decision-making.
* **Developer-Centric**: Built by developers, for developers, with extensive documentation and support.

Whether you're building the next big DeFi application, managing a diverse crypto portfolio, or exploring the frontiers of blockchain technology, UseMoon.ai provides the tools and capabilities you need to succeed in the decentralized world.

Join us on our mission to make DeFi accessible, efficient, and powerful for everyone. With UseMoon.ai, the future of finance is at your fingertips.

Ready to start your DeFi journey? Sign up now and experience the UseMoon.ai difference!


# What Can Moon Do?

### General Overview

Moon is a highly composable wallet and authentication product designed to simplify user-friendly, AI-compatible dApp development. Moon is compatible with all standard EVM blockchains, as well as Bitcoin & Cosmos-based chains, allowing developers to offer users a universal experience regardless of where their apps are built.

Moon enables users to onboard to Web3 apps using their existing social accounts (Google, Twitter, Instagram, etc.) for authentication, greatly lowering the barrier of entry for users unfamiliar with blockchain technology. More experienced users can authenticate using their existing EVM wallets. Mobile users can also authenticate using Passkey for a highly-secure, hardware-based authentication method.

Once authenticated, a wallet is created for users, allowing them to interact with any Web3-enabled features in your app. The easiest way to build an app with Moon is through the [SDK](/sdks), and for already-built apps seeking to integrate Web3 technology, an extensive [API](broken://pages/ohJk6g5swxwb1zIt77sF) can be utilized to easily enable users to perform blockchain operations, such as transfers & smart contract interactions, within your app.

Moon also features an extensive library for building AI-augmented applications using [Langchain](/ai/langchain-1).\ <br>

### High-Level Architecture

![](/files/Ye5wQYZvzizHoMtdA1rv)

The Moon API, specifically designed for Moon's wallet, authentication, and data infrastructure, integrates mpc-tts + hsm via HashiCorp Vault for secure storage of authenticated private keys. It enables users to sign transactions from their wallets and obtain a secure JSON Web Token (JWT).

Users can construct and sign transactions using methods akin to those in ethers.js, facilitating interaction with the blockchain through custom APIs and account abstraction mechanisms. The transaction data is then accessible for further operations.

Moon offers a robust package ecosystem with support for a variety of libraries and languages. This includes viem, wagmi, and rainbowkit for front-end development, ethers for Ethereum blockchain interactions, and programming languages such as Golang, Python, and Langchain for backend development. This diverse support allows developers to choose the tools that best fit their project requirements, promoting flexibility and efficiency in development.\ <br>


# What are Moon’s Use Cases?

* **DeFi Infrastructure:** Moon's SDK enables DeFi development, including lending protocols, trading bots, and yield farming strategies.
* **Web3 Security Integration:** Moon’s authentication capabilities can onboard users with traditional web2 front-ends backed by web3 security.
* **NFT Marketplaces:** Developers can build NFT marketplaces with Moon's SDK, featuring secure asset trading and authentication functionalities.
* **Blockchain Gaming Platforms:** Moon empowers the creation of blockchain gaming platforms with secure asset ownership and fair gameplay.
* **Identity Verification:** Moon's authentication capabilities can be used for a plethora of decentralized identity solutions, including chatbots and social media platforms.
* …and more!!


# What Features Come with Moon?

* **Wallet as a Service:** Composable wallet infrastructure for flexible and seamless integration.
* **Authentication as a Service:** Ensures secure authentication with support for OAuth2, bio-metric and passkey, and SIWE (Sign-In With Ethereum) -- combining robust security with ease of use.
* **AI:** Langchain integration & transaction library for building AI-powered blockchain apps.
* **Account Abstraction:** ERC-4337 smart accounts on supported chains enable gas sponsorship, UserOp transactions, and more


# Supported Networks

* Bitcoin
* Litecoin
* Dogecoin
* Bitcoin Cash
* EOS
* Tron
* Ripple
* EVM - all networks on chainlist


# Getting started with moon

## Getting Started with @moonup/create

Welcome to the @moonup/create package documentation! This powerful tool allows you to quickly set up a new Next.js project with various configurable options, tailored for blockchain and DeFi development.

### Introduction

@moonup/create is a CLI tool that helps you bootstrap a new Next.js project with additional features specifically designed for blockchain and DeFi applications. It provides a seamless way to create a new project with options for TypeScript, ESLint, PWA support, Moon Wallet integration, and more.

### Prerequisites

Before you begin, make sure you have Node.js installed on your system. We recommend using the latest LTS version.

### Creating a New Project

To create a new project using @moonup/create, run the following command in your terminal:

```bash
npx @moonup/create@latest
```

This command will start an interactive process where you'll be prompted to make choices about your project setup.

### Configuration Options

During the project creation process, you'll be asked a series of questions to customize your setup:

1. **Project Name**: Choose a name for your project. This will be used as the directory name and in your package.json.
2. **TypeScript**: Decide whether to use TypeScript in your project.
3. **ESLint**: Choose if you want to include ESLint for code linting.
4. **PWA (Progressive Web App)**: Opt to include PWA support for your application.
5. **Moon Wallet**: Decide if you want to integrate Moon Wallet into your project.
6. **Tailwind CSS**: Choose whether to include Tailwind CSS for styling.
7. **src/ Directory**: Decide if you want to use a `src/` directory for your source files.
8. **Custom Import Alias**: Choose if you want to customize the default import alias (@/\*).
9. **Rainbowkit Connect**: Decide if you want to integrate Rainbowkit for wallet connections.
10. **Wallet Connect**: Choose whether to include Wallet Connect integration.

### Project Structure

After the creation process, your project will have a structure similar to a standard Next.js project, with additional files and configurations based on your choices. Here's a basic overview:

```
my-app/
├── pages/
│   ├── _app.js
│   └── index.js
├── public/
├── styles/
├── package.json
├── next.config.js
└── README.md
```

Additional files and directories will be present based on your configuration choices.

### Next Steps

1. Navigate to your project directory:

   ```bash
   cd my-app
   ```
2. Install dependencies:

   ```bash
   npm install
   ```

   or

   ```bash
   yarn
   ```
3. Start the development server:

   ```bash
   npm run dev
   ```

   or

   ```bash
   yarn dev
   ```
4. Open <http://localhost:3000> in your browser to see your application.

### Additional Features

#### Moon Wallet Integration

If you chose to include Moon Wallet, you'll find additional components and hooks in your project for easy blockchain interactions. Refer to the Moon Wallet documentation for more details on usage.

#### Tailwind CSS

If you opted for Tailwind CSS, your project will be set up with the necessary configurations. You can start using Tailwind classes in your components right away.

#### TypeScript

For TypeScript projects, you'll find .ts and .tsx files instead of .js and .jsx. TypeScript configurations will be automatically set up for you.

#### PWA Support

If you chose PWA support, your project will include the necessary service worker and manifest files. Make sure to customize these for your specific application needs.

### Customization

Feel free to modify any of the generated files to suit your project needs. The next.config.js file is a great place to start for Next.js-specific configurations.

### Conclusion

@moonup/create provides a solid foundation for building blockchain and DeFi applications with Next.js. It combines the power of Next.js with additional tools and integrations commonly used in blockchain development.

For more information on Next.js features and API, check out the Next.js documentation.

Happy coding with @moonup/create and Next.js!


# Authentication

## Supported Authentication Methods

Usemoon.ai supports various authentication methods to ensure a secure and convenient user experience. These methods include:

### Email and Password

A user can log in with their email and password. This method is a traditional way to authenticate users and is widely used.

[#email-and-password](#email-and-password "mention")

### OAuth2 Login with Moon

This method allows users to log in using OAuth2, which is a standard protocol for authorization. It provides a secure and efficient way to authenticate users without sharing their passwords.

[Login with Moon](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/oauth-2-0-bb827a25ff8f4952abd36548961d97be)

### OAuth2 with Custom Providers

In addition to Moon's OAuth2 login, usemoon.ai also supports OAuth2 with custom providers. This means you can integrate with your existing authentication system or use a third-party provider to authenticate users.

[OAuth 2.0](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/oauth-2.0)

### Sign In with Ethereum (SIWE)

Usemoon.ai supports Ethereum address login using SIWE. This method allows users to log in using their Ethereum address and a signature, which is a secure and decentralized way to authenticate users.

[Sign in with Ethereum](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/siwe-d911f742cd684feca1f334c41c785602)

### WebAuthn/Passkey Authentication

Usemoon.ai supports WebAuthn/Passkey authentication, which is a standard for passwordless authentication using public key cryptography. This method provides a secure and convenient way to authenticate users without the need for passwords.

[Passkey](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/passkey)

### API Key Authentication

Usemoon.ai also offers an authentication method that provides an infinite expiry token. This method uses an API key and is ideal for scenarios requiring sustained access without the need for session renewal. This is particularly useful for developer-facing applications where automation processes may be necessary.

[API Key](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/api-key)

### Embedded Accounts

Usemoon.ai supports embedded accounts, which allow users to create an account within another application. This method provides a seamless user experience and eliminates the need for users to create a separate account.

[Embedded accounts](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/embedded-accounts)

### Token Refreshing

Usemoon.ai supports token refreshing, which allows users to obtain a new access token without having to re-authenticate. This method provides a convenient way to maintain access to protected resources without the need for users to re-enter their credentials.

[Token Refreshing](/authentication-750f0518f1d64f82a7ef38dd5cbc4b64/token-refreshing)


# Email and password

### Authentication Methods

The `MoonSDK` class provides the following authentication methods:

#### 1. Email and Password Authentication

The `signUp` and `signInWithPassword` methods allow users to create an account or sign in using their email address and password. Here's how to use them:

<pre class="language-javascript"><code class="lang-javascript">import { MoonSDK } from '@moonup/moon-sdk';

<strong>const moonSDK = new MoonSDK(config);
</strong>
async function signUpWithEmailAndPassword(email, password) {
  try {
    await moonSDK.signUp(email, password);
    console.log('Account created successfully.');
  } catch (error) {
    console.error('Error creating account:', error);
  }
}

async function signInWithEmailAndPassword(email, password) {
  try {
    await moonSDK.signInWithPassword(email, password);
    console.log('Signed in successfully.');
  } catch (error) {
    console.error('Error signing in:', error);
  }
}
</code></pre>

#### 2. Phone Number Authentication

The `signInWithPhone` method allows users to sign in using their phone number and password. Here's how to use it:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const moonSDK = new MoonSDK(config);

async function signInWithPhone(phone, password) {
  try {
    await moonSDK.signInWithPhone(phone, password);
    console.log('Signed in successfully.');
  } catch (error) {
    console.error('Error signing in:', error);
  }
}
```


# OAuth 2.0

## OAuth2 Authentication in MoonSDK

MoonSDK supports OAuth2 authentication with various providers, allowing users to log in using their existing accounts on these platforms. This documentation page explains how to use the MoonSDK class functions for OAuth2 authentication and provides examples of the process of redirection to code exchange for a session token.

### Available Providers

MoonSDK supports the following OAuth2 providers:

* Discord
* GitHub
* Google
* Twitter

### OAuth2 Authentication Process

The OAuth2 authentication process involves the following steps:

1. Redirect the user to the OAuth2 login page of the provider.
2. The user logs in to their account on the provider's website.
3. The provider redirects the user back to your application with a code.
4. Exchange the code for a session token.

### Example: Discord OAuth2 Authentication

Here's an example of how to use the `performDiscordOAuth` and `performDiscordOauthCodeExchange` functions to authenticate a user with Discord:

1. Redirect the user to the Discord OAuth2 login page:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK({
  clientId: 'YOUR_CLIENT_ID',
});

sdk.performDiscordOAuth();
```

2. The user logs in to their Discord account and is redirected back to your application with a code in the URL query string.
3. Exchange the code for a session token:

```javascript
const code = new URLSearchParams(window.location.search).get('code');
const token = await sdk.performDiscordOauthCodeExchange(code);
```

The `performDiscordOauthCodeExchange` function sends a request to the Discord API to exchange the code for a session token and returns the token.

### Example: GitHub OAuth2 Authentication

Here's an example of how to use the `performGithubOAuth` and `performGithubOauthCodeExchange` functions to authenticate a user with GitHub:

1. Redirect the user to the GitHub OAuth2 login page:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK({
  clientId: 'YOUR_CLIENT_ID',
});

sdk.performGithubOAuth();
```

2. The user logs in to their GitHub account and is redirected back to your application with a code in the URL query string.
3. Exchange the code for a session token:

```javascript
const code = new URLSearchParams(window.location.search).get('code');
const token = await sdk.performGithubOauthCodeExchange(code);
```

The `performGithubOauthCodeExchange` function sends a request to the GitHub API to exchange the code for a session token and returns the token.

### Example: Google OAuth2 Authentication

Here's an example of how to use the `performGoogleOAuth` and `performGoogleOauthCodeExchange` functions to authenticate a user with Google:

1. Redirect the user to the Google OAuth2 login page:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK({
  clientId: 'YOUR_CLIENT_ID',
});

sdk.performGoogleOAuth();
```

2. The user logs in to their Google account and is redirected back to your application with a code in the URL query string.
3. Exchange the code for a session token:

```javascript
const code = new URLSearchParams(window.location.search).get('code');
const token = await sdk.performGoogleOauthCodeExchange(code);
```

The `performGoogleOauthCodeExchange` function sends a request to the Google API to exchange the code for a session token and returns the token.

### Example: Twitter OAuth2 Authentication

Here's an example of how to use the `performTwitterOauth` and `performTwitterOauthCodeExchange` functions to authenticate a user with Twitter:

1. Redirect the user to the Twitter OAuth2 login page:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK({
  clientId: 'YOUR_CLIENT_ID',
});

sdk.performTwitterOauth();
```

2. The user logs in to their Twitter account and is redirected back to your application with a code in the URL query string.
3. Exchange the code for a session token:

```javascript
const code = new URLSearchParams(window.location.search).get('code');
const token = await sdk.performTwitterOauthCodeExchange(code);
```

The `performTwitterOauthCodeExchange` function sends a request to the Twitter API to exchange the code for a session token and returns the token.

### Conclusion

MoonSDK supports OAuth2 authentication with various providers, allowing users to log in using their existing accounts on these platforms. This documentation page explains how to use the MoonSDK class functions for OAuth2 authentication and provides examples of the process of redirection to code exchange for a session token. Whether you're building a new application or looking to improve the authentication flow of an existing one, MoonSDK's OAuth2 support is a great choice.


# Login with Moon

## Using Moon OAuth2 Provider for Authentication

OAuth 2.0 is a widely-used authorization framework that allows users to grant third-party applications limited access to their resources without sharing their login credentials. Moon, a platform, supports OAuth 2.0 for user authentication. This guide will walk you through the process of implementing OAuth 2.0 into a Moon-integrated app.

The implementation process involves four main steps:

### Step 1: Grab Environment Variables from Moon

To begin, visit Moon's documentation or support page to obtain the necessary environment variables. Add these variables to your project's `.env` file. Below is an example of the variables your `.env` file should include:

```
NODE_PORT=4000
REACT_APP_CLIENT_ID=your_client_id
REACT_APP_CLIENT_SECRET=your_client_secret
REACT_APP_RESPONSE_TYPE=code
REACT_APP_REDIRECT_URI=http://example.com/authorize
REACT_APP_SCOPE=
REACT_APP_STATE=
NODE_GRANT_TYPE=authorization_code
```

### Step 2: Initiate the Authentication Process

To start the authentication process, redirect the user to Moon's OAuth 2.0 authorization page. This can be done by triggering a redirect from your application's login interface. Use the environment variables obtained in the previous step to construct the redirect URL.

Here's an example of how to implement this in a React component:

```javascript
// LoginButton.tsx
import React from 'react';

function LoginButton() {
  const handleClick = () => {
    const {
      REACT_APP_RESPONSE_TYPE,
      REACT_APP_CLIENT_ID,
      REACT_APP_REDIRECT_URI,
      REACT_APP_SCOPE,
      REACT_APP_STATE,
    } = process.env;

    const redirectUrl = `https://dash.usemoon.ai/authorize?response_type=${REACT_APP_RESPONSE_TYPE}&client_id=${REACT_APP_CLIENT_ID}&redirect_uri=${REACT_APP_REDIRECT_URI}&scope=${REACT_APP_SCOPE}&state=${REACT_APP_STATE}`;

    window.location.href = redirectUrl;
  };

  return <button onClick={handleClick}>Login with Moon</button>;
}

export default LoginButton;
```

### Step 3: Handle the Redirect from the Authorization Server

After the user logs in to Moon's separate login page and authorizes the application, they will be redirected back to your application to the URI specified by `redirect_uri`. Your application needs to handle this redirection and extract the authorization code from the URL.

Here's an example of how to implement this in a React component:

```javascript
// OAuth2Callback.ts
import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useMoonSDK } from '@moonup/react';

function OAuth2Callback() {
  const location = useLocation();
  const { moon } = useMoonSDK();

  useEffect(() => {
    const fetchData = async () => {
      // Extract the 'code' parameter from the URL query string.
      const urlParams = new URLSearchParams(location.search);
      const code = urlParams.get('code');

      if (code) {
        // Use the authorization code to request an access token.
        try {
          const response = await fetch(`http://localhost:4000/callback?code=${code}`, {
            headers: { 'Content-Type': 'application/json' },
          });
          const data = await response.json();

          // Set the access token in the client application for making authenticated requests.
          moon?.setAccessToken(data.access_token, data.refresh_token);
        } catch (error) {
          console.error('Authentication error:', error);
        }
      }
    };

    fetchData();
  }, [location, moon]);

  return <div>Processing OAuth2 callback...</div>;
}

export default OAuth2Callback;
```

### Step 4: Exchange the Authorization Code for an Access Token

The final step involves exchanging the authorization code for an access token. This step is typically performed by the backend server to keep the client secret confidential.

Here's an example of how to implement this in a Node.js server:

```javascript
// server/index.ts
import express, { Request, Response } from 'express';
import axios from 'axios';

const app = express();

app.get('/callback', async (req: Request, res: Response) => {
  try {
    const { code, state } = req.query;
    const {
      REACT_APP_GRANT_TYPE,
      REACT_APP_CLIENT_ID,
      REACT_APP_CLIENT_SECRET,
      REACT_APP_REDIRECT_URI,
    } = process.env;

    const response = await axios.post(
      'https://dash.usemoon.ai/api/oauth2/exchange',
      {
        grant_type: REACT_APP_GRANT_TYPE,
        code: code,
        client_id: REACT_APP_CLIENT_ID,
        client_secret: REACT_APP_CLIENT_SECRET,
        redirect_uri: REACT_APP_REDIRECT_URI,
      },
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );

    res.cookie('sb-api-auth-token', response.data);
    res.json(response.data);
  } catch (error) {
    console.error('Server error:', error);
    return res.status(500).json({
      error: 'Server error. Try again with a different prompt.',
      success: false,
    });
  }
});

app.listen(process.env.NODE_PORT, () => {
  console.log(`Server is running on port ${process.env.NODE_PORT}`);
});
```

By following these steps, you can successfully implement OAuth 2.0 authentication using Moon in your application.


# API Key

Sure, here's a revised version of the documentation page that uses the term "API tokens" instead of "X-API-Key/API tokens":

## API Token Authentication

Moon supports the use of API tokens for authentication in API requests. This allows developers to secure their requests to the Moon API using a token, rather than using OAuth2 authentication.

### Using API Tokens

To use API tokens for authentication, follow these steps:

1. Obtain an API token from the Moon dashboard.
2. Include the `X-API-Key` header in your API requests, with the value set to your API token.

Here's an example of how to include the `X-API-Key` header in an API request using the `fetch` API:

```javascript
const apiToken = 'YOUR_API_TOKEN';

async function getAccounts() {
  try {
    const response = await fetch('https://beta.usemoon.ai/api/v1/accounts', {
      headers: {
        'X-API-Key': apiToken,
      },
    });
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getAccounts();
```

In this example, the `fetch` method is used to send a GET request to the Moon API's `/api/v1/accounts` endpoint. The `headers` option is used to include the `X-API-Key` header in the request, with the value set to the API token obtained from the Moon dashboard.

### Using API Tokens with the `@moonup/moon-api` Package

The `@moonup/moon-api` package also supports the use of API tokens for authentication. To use API tokens with the `@moonup/moon-api` package, configure the `securityWorker` function in the `ApiConfig` object to include the `X-API-Key` header in the request.

Here's an example of how to configure the `securityWorker` function to include the `X-API-Key` header in an API request using the `@moonup/moon-api` package:

```javascript
import { Accounts, ApiConfig, ContentType, HttpClient } from '@moonup/moon-api';

const baseApiParams: ApiConfig = {
  baseUrl: 'https://beta.usemoon.ai',
  baseApiParams: {
    secure: true,
    type: ContentType.Json,
    format: 'json',
  },
  securityWorker: async (securityData) => {
    return Promise.resolve({
      headers: {
        'X-API-Key': securityData.token,
      },
    });
  },
};

const http = new HttpClient(baseApiParams);
const accountsSDK = new Accounts(http);

async function listAccounts() {
  const response = await accountsSDK.listAccounts();
  console.log(response.data);
}

listAccounts();
```

In this example, the `securityWorker` function is configured to include the `X-API-Key` header in the request, with the value set to the API token obtained from the Moon dashboard. The `Accounts` SDK is then used to send a request to the Moon API's `/api/v1/accounts` endpoint, which is authenticated using the `X-API-Key` header.

### Security Considerations

When using API tokens for authentication, it's important to ensure that your API token is kept secure. Never expose your API token in client-side code or include it in version control systems. Instead, store your API token in a secure environment variable or configuration file.

### Conclusion

The use of API tokens for authentication is a convenient way to secure API requests to the Moon API. By including the `X-API-Key` header in your requests, you can easily authenticate your requests using a token. Whether you're using the `@moonup/moon-api` package or making requests using a library like `fetch`, the process is similar. Just remember to keep your API token secure and be aware of the rate limits imposed by Moon.


# Sign in with Ethereum

## SIWE User Authentication using an Ethereum Address

Moon allows an app to authenticate a user using SIWE (Sign in with Ethereum). The process to implement SIWE into a Moon app involves the following steps:

### Step 1: Fetch a Nonce from Moon

The first step in the SIWE authentication process is to obtain a nonce by calling the `getSIWENonce` method from the `MoonSDK` class and passing the user's Ethereum address. Moon will then generate a nonce, associate it with the user's session, and return it.

#### What is a nonce?

A nonce is a random number that can be used just once in a cryptographic communication. It is used here to prevent replay attacks, where an attacker might try to re-send a previous request to gain unauthorized access.

Here is an example of how to retrieve a nonce from Moon using the `MoonSDK` class:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK();

const nonce = await sdk.getSIWENonce(USER_ADDRESS_HERE);
```

### Step 2: User Signs a Message

Once the nonce is fetched, the user is prompted to sign a message. This message includes the nonce and other details about the sign-in request, structured according to the SIWE format. This step is crucial for verifying the user's control over the Ethereum address without exposing any sensitive information like private keys.

Here is an example of how to have a user sign a message with the nonce using the `signMessage` function from `@wagmi/core` and the `SiweMessage` class from `siwe`:

```javascript
import { signMessage } from '@wagmi/core';
import { SiweMessage } from 'siwe';

const message = new SiweMessage({
    domain: window.location.host,
    address: address,
    statement: 'Sign in with Ethereum to the app.',
    uri: window.location.origin,
    version: '1',
    chainId: 1,
    nonce: nonce,
});
const signedMessage = await signMessage({
    message: message.prepareMessage(),
});
```

#### How does this code prompt the user?

The above example uses the `signMessage` function to prompt the user to connect their wallet through their wallet connector (like MetaMask or Coinbase Wallet) and then have the user "sign the message" which logs them into the app!

### Step 3: Verify the SIWE Signature

After obtaining the signed message, the next step is to verify the SIWE signature using the `verifySIWESignature` method from the `MoonSDK` class. This method takes the user's Ethereum address, the signed message, the nonce, and the message as parameters.

Here is an example of how to verify the SIWE signature using the `MoonSDK` class:

```javascript
const siweResponse = await sdk.verifySIWESignature(userAddress, signedMessage, nonce, message);
```

### Step 4: Handle Final Response from Moon’s Server

If a user has been successfully authorized, setting the access token on an active `MoonSDK` instance will finish authenticating the user!

```javascript
if (siweResponse.ok) {
    // Verification was successful
    moon.setAccessToken(siweResponse.access_token, siweResponse.refresh_token);
    console.log('Verification successful!');
} else {
    // Verification failed
    console.error('Verification failed!');
}
```

### Full code for example:

Put together, below is an entire code sample for how to authenticate a user using SIWE:

```javascript
import { signMessage } from '@wagmi/core';
import { SiweMessage } from 'siwe';
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK();

const MoonSIWE = async (address) => {
    const userAddress = address ? address : '';

    try {
        // 1. Get a nonce from the server using MoonSDK
        const nonce = await sdk.getSIWENonce(userAddress);

        // 2. Ask the user to sign a message
        const message = new SiweMessage({
            domain: window.location.host,
            address: userAddress,
            statement: 'Sign in with Ethereum to the app.',
            uri: window.location.origin,
            version: '1',
            chainId: 1,
            nonce: nonce,
        });
        const signedMessage = await signMessage({
            message: message.prepareMessage(),
        });

        // 3. Verify the SIWE signature using MoonSDK
        const siweResponse = await sdk.verifySIWESignature(userAddress, signedMessage, nonce, message);

        // 4. Handle final response from Moon’s server
        if (siweResponse.ok) {
            // Verification was successful
            moon.setAccessToken(siweResponse.access_token, siweResponse.refresh_token);
            console.log('Verification successful!');
        } else {
            // Verification failed
            console.error('Verification failed!');
        }
    } catch (err) {
        console.error('An error occurred:', err);
    }
}
```

In this documentation page, the new methods `getSIWENonce` and `verifySIWESignature` from the `MoonSDK` class are used to handle the SIWE (Sign-In with Ethereum) flow. The `getSIWENonce` method retrieves a nonce from the server, and the `verifySIWESignature` method verifies the SIWE signature using the provided address, signed message, nonce, and message.


# Passkey

## WebAuthn in MoonSDK

WebAuthn is a web standard published by the World Wide Web Consortium (W3C) that enables passwordless logins on the web. It allows users to use local authenticators (such as biometrics or FIDO2 devices) to securely authenticate to web applications. MoonSDK uses WebAuthn to provide a secure and user-friendly authentication method.

### React WebAuthn Component

Here's a simplified example of a React component that uses WebAuthn for registration and login using the MoonSDK class functions:

```javascript
import React, { useState } from 'react';
import { startAuthentication, startRegistration } from '@simplewebauthn/browser';
import { MoonSDK } from '@moonup/moon-sdk';

const sdk = new MoonSDK();

function WebAuthnComponent() {
  const [email, setEmail] = useState('');

  const handleLogin = async () => {
    const auth = await sdk.handlePassKeyLogin(email);
    const credential = await startAuthentication(auth);
    const response = await sdk.handlePasskeyLoginVerify(email, credential);
  };

  const handleRegister = async () => {
    const options = await sdk.handleRegister(email);
    const credential = await startRegistration(options);
    const token = await sdk.handleRegisterVerify(email, credential, options);
  };

  return (
    <div>
      <input type="email" onChange={(e) => setEmail(e.target.value)} />
      <button onClick={handleLogin}>Login with WebAuthn</button>
      <button onClick={handleRegister}>Register with WebAuthn</button>
    </div>
  );
}

export default WebAuthnComponent;
```

This component includes an input field for the user's email and two buttons for login and registration. When the user clicks on the login or register button, the corresponding handler function is called. These functions use the MoonSDK class functions to interact with the server and the user's authenticator. After the user has authenticated with their authenticator, the credential is sent to the server for verification.

### WebAuthn in MoonSDK

WebAuthn in MoonSDK provides a secure and user-friendly authentication method. By using local authenticators, users can log in to web applications without remembering and typing passwords. MoonSDK's React WebAuthn component simplifies the integration of WebAuthn into your application, allowing users to easily register and log in using their authenticators.

### Benefits of WebAuthn in MoonSDK

* Security: WebAuthn provides strong security guarantees, making it a secure choice for authentication.
* User-friendly: WebAuthn allows users to log in using local authenticators, such as biometrics or FIDO2 devices, making the authentication process more user-friendly.
* Simplified integration: MoonSDK's React WebAuthn component simplifies the integration of WebAuthn into your application, making it easy to add WebAuthn support to your project.

### Conclusion

WebAuthn is a powerful authentication method that provides strong security guarantees and a user-friendly experience. MoonSDK's React WebAuthn component simplifies the integration of WebAuthn into your application, making it easy to add WebAuthn support to your project. Whether you're building a new application or looking to improve the security and usability of an existing one, WebAuthn in MoonSDK is a great choice.


# Embedded accounts

Moon Supports Embedded Account Endpoint for Seamless Integration with Existing Authentication Solutions

Moon supports an embedded account endpoint that allows users to create sub-accounts and associate wallets with those accounts. This endpoint enables seamless integration with existing authentication solutions, allowing developers to create sub-accounts for their users and associate wallets with those accounts.

Using the Embedded Account Endpoint

To use the embedded account endpoint, send a POST request to the `/client` endpoint of the Moon API. The request should include the following headers and payload:

* Headers:
  * Authorization: A valid API token or OAuth2 access token.
  * Content-Type: application/json
* Payload:
  * name: A unique name for the sub-account.
  * metadata: Optional metadata for the sub-account.

Here's an example of how to use the embedded account endpoint using the `fetch` API:

```javascript
async function createEmbeddedAccount(email, domain, userId) {
  const url = 'https://beta.usemoon.ai/client';
  const headers = {
    'X-API-KEY': 'YOUR_API_TOKEN',
    'Content-Type': 'application/json',
  };
  const body = JSON.stringify({
    name: email,
    metadata: {
      from: domain,
      user: userId,
    },
  });
  const requestOptions = {
    method: 'POST',
    headers: headers,
    body: body,
    redirect: 'follow',
  };

  try {
    const response = await fetch(url, requestOptions);
    const result = await response.text();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}
createEmbeddedAccount('user@example.com', 'mydomain.com', '1234567890');
```

In this example, the `fetch` API is used to send a POST request to the `/client` endpoint of the Moon API. The request includes the `Authorization` header, which is set to a valid API token or OAuth2 access token. The request also includes the `Content-Type` header, which is set to `application/json`. The payload of the request is a JSON object that includes the `name` and `metadata` properties for the sub-account.

The response from the API will include the details of the newly created sub-account, including its unique ID and the associated wallets.

Benefits of Using the Embedded Account Endpoint

Using the embedded account endpoint provides the following benefits:

* Seamless integration with existing authentication solutions: The embedded account endpoint enables seamless integration with existing authentication solutions, allowing developers to create sub-accounts for their users and associate wallets with those accounts.
* Fine-grained access control: The embedded account endpoint allows for fine-grained access control, enabling developers to restrict access to specific resources or actions for individual sub-accounts.
* Scalability: The embedded account endpoint enables scalability, allowing developers to create and manage multiple sub-accounts for their users as their application grows.

Conclusion

The embedded account endpoint is a powerful feature that enables seamless integration with existing authentication solutions. By using the embedded account endpoint, developers can create sub-accounts for their users and associate wallets with those accounts, providing fine-grained access control and scalability. Whether you're building a new application or integrating Moon into an existing one, the embedded account endpoint is a valuable tool that can help you meet your users' needs.


# Token Refreshing

## `Token Refreshing`

The `/auth/refresh` endpoint is a POST request that is used to refresh a user's session. This is particularly useful when the user's session has expired and needs to be renewed.

The Moon SDK will automatically refresh the user's session when it expires. This means that you don't have to manually refresh the session in most cases. However, this endpoint is still useful in scenarios where you need to manually control the session refresh.

### Request

The request should include a `refresh_token` in the body. This token is used to authenticate the user and generate a new session.

```json
{
  "refresh_token": "your_refresh_token_here"
}
```

### Response

The response will return the new session data if the request is successful. If there is an error, it will return a 500 status code along with the error message.

### Code Example

Here is an example of how to use this endpoint:

```typescript
import axios from 'axios';

const refreshToken = 'your_refresh_token_here';

axios.post('https://beta.usemoon.ai/auth/refresh', { refresh_token: refreshToken })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
```


# Interacting with the blockchain


# EVM

## Interacting with EVM Transactions using MoonSDK

This tutorial will guide you through the process of sending an EVM transaction using MoonSDK. We will cover sending transactions with and without encoded ABI data, as well as creating and listing accounts.

### Prerequisites

* Node.js installed on your machine
* An EVM-compatible account with some balance
* Moon API key (optional, but required for some features)

### Installation

First, install the required dependencies:

```bash
npm install @moonup/moon-sdk ethers
```

### Initialization

Create a new file, `evm_transaction.ts`, and import the necessary modules:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { ethers } from 'ethers';
import { InputBody, BroadcastInput } from '@moonup/moon-api';
```

Initialize the MoonSDK with your API key (if you have one):

```javascript
const sdk = new MoonSDK({
  apiKey: 'your_moon_api_key',
});
```

### Sending a Transaction without Encoded ABI Data

To send a transaction without encoded ABI data, you need to prepare the transaction data, sign the transaction, and broadcast it to the blockchain.

#### Step 1: Prepare the Transaction Data

Store data pertaining to the transaction in an InputBody object:

```javascript
const amountInWei = ethers.utils.parseUnits(amountEth, 'ether');
const transactionData: InputBody = {
  to: toAddress,
  value: amountInWei.toString(),
  chain_id: chainId,
  encoding: 'utf-8',
};
```

#### Step 2: Sign the Transaction

Use the signTransaction function to sign the transaction and get the raw transaction string to broadcast the transaction:

```javascript
const signedTransactionData = await sdk.getAccountsSDK().signTransaction(account, transactionData);
const rawTransaction = signedTransactionData.data.data.transactions[0].raw_transaction;
```

#### Step 3: Broadcast the Signed Message to the Blockchain

Store the raw signed transaction string into a BroadcastInput object and use the input object to broadcast the transaction using broadcastTx:

```javascript
const broadcastInput: BroadcastInput = {
  chainId: chainId,
  rawTransaction: rawTransaction,
};
const broadcastResponse = await sdk.getAccountsSDK().broadcastTx(account, broadcastInput);
```

### Sending a Transaction with Encoded ABI Data

To send a transaction with encoded ABI data, you need to encode the data, prepare the transaction data, sign the transaction, and broadcast it to the blockchain.

#### Step 1: Encode the ABI Data

Encode the ABI data using ethers.js:

<pre class="language-typescript"><code class="lang-typescript"><strong>const abi = [{
</strong>	"constant": false,
	"inputs": [
		{
			"name": "_from",
			"type": "address"
		},
		{
			"name": "_to",
			"type": "address"
		},
		{
			"name": "_value",
			"type": "uint256"
		}
	],
	"name": "transferFrom",
	"outputs": [
		{
			"name": "success",
			"type": "bool"
		}
	],
	"payable": false,
	"stateMutability": "nonpayable",
	"type": "function"
}]
const functionName = "transferFrom"
const params = []


const encodedData = new ethers.utils.Interface(abi).encodeFunctionData(functionName, params);
</code></pre>

#### Step 2: Prepare the Transaction Data

Store data pertaining to the transaction in an InputBody object, including the encoded data:

```javascript
const transactionData: InputBody = {
  to: contractAddress,
  data: encodedData,
  chain_id: chainId,
  encoding: 'utf-8',
  value: "0",
  chain_id: chainId,
  encoding: 'utf-8',
};
```

#### Step 2: Sign the Transaction

Use the signTransaction function to sign the transaction and get the raw transaction string to broadcast the transaction:

```javascript
const signedTransactionData = await sdk.getAccountsSDK().signTransaction(account, transactionData);
const rawTransaction = signedTransactionData.data.data.transactions[0].raw_transaction;
```

#### Step 3: Broadcast the Signed Message to the Blockchain

Store the raw signed transaction string into a BroadcastInput object and use the input object to broadcast the transaction using broadcastTx:

```javascript
const broadcastInput: BroadcastInput = {
  chainId: chainId,
  rawTransaction: rawTransaction,
};
const broadcastResponse = await sdk.getAccountsSDK().broadcastTx(account, broadcastI
```

### Creating and Listing Accounts

You can create a new account using the createAccount function and list all accounts using the listAccounts function.

#### Creating an Account

To create a new account, use the createAccount function:

```javascript
const newAccount = await sdk.getAccountsSDK().createAccount({});
```

#### Listing Accounts

To list all accounts, use the listAccounts function:

```javascript
const accounts = await sdk.getAccountsSDK().listAccounts();
```

### Conclusion

You have successfully sent EVM transactions using MoonSDK, both with and without encoded ABI data, and created and listed accounts. You can now use MoonSDK to interact with various blockchain networks and services.


# Solana

## Interacting with the Blockchain using MoonSDK on Solana

This tutorial will guide you through the process of initializing the MoonSDK, creating a Solana transaction, signing the transaction, and sending it to the Solana network.

### Prerequisites

* Node.js installed on your machine
* A Solana account with some SOL balance
* Moon API key (optional, but required for some features)

### Installation

First, install the required dependencies:

```bash
npm install @solana/web3.js @moonup/moon-sdk
```

### Initialization

Create a new file, `solana_transaction.js`, and import the necessary modules:

```javascript
import web3, { PublicKey, Transaction } from '@solana/web3.js';
import { MoonSDK } from '@moonup/moon-sdk';
```

Initialize the MoonSDK with your API key (if you have one):

```javascript
const sdk = new MoonSDK({
  apiKey: 'your_moon_api_key',
});
```

### Creating a Solana Transaction

Connect to the Solana network:

```javascript
const connection = new web3.Connection(
  web3.clusterApiUrl('devnet'),
  'confirmed'
);
```

List your Solana accounts using the MoonSDK:

```javascript
const accounts = await sdk.getSolanaSDK().listAccounts();
console.log(accounts);
```

Or create a new solana account using the MoonSDK<br>

```typescript
const accounts = await sdk.getSolanaSDK().createAccount({});
console.log(accounts);
```

Select the first account as the payer and create a new Solana account as the recipient:

```javascript
const payer = new PublicKey(accounts[0]);
const toAccount = new PublicKey("toAccount");
```

Manually construct the transaction:

```javascript
const recentBlockhash = await connection.getLatestBlockhash();
const manualTransaction = new Transaction({
  recentBlockhash: recentBlockhash.blockhash,
  feePayer: payer,
});
manualTransaction.add(
  web3.SystemProgram.transfer({
    fromPubkey: payer,
    toPubkey: toAccount.publicKey,
    lamports: 1,
  })
);
```

### Signing the Transaction

Serialize the transaction and sign it using the MoonSDK:

```javascript
const serialise = manualTransaction.serialize({
  verifySignatures: false,
  requireAllSignatures: false,
});
const signature = await sdk.getSolanaSDK().signTransaction(accounts[0], {
  unsigned_tx: serialise.toString('base64'),
  network: 'devnet',
});
```

### Sending the Transaction

Send the signed transaction to the Solana network:

```javascript
const hash = await connection.sendRawTransaction(signature.signed_tx);
console.log(hash);
```

### Full Example

```typescript
import web3, { PublicKey, Transaction } from '@solana/web3.js';
import { MoonSDK } from '@moonup/moon-sdk';

export const signAndSend = async () => {
  // const payer = web3.Keypair.generate();
  const connection = new web3.Connection(
    web3.clusterApiUrl('devnet'),
    'confirmed'
  );

  const sdk = new MoonSDK();

  const accounts = await sdk.getSolanaSDK().listAccounts();
  console.log(accounts);
  const payer = new PublicKey(accounts[0]);
  const toAccount = new PublicKey("toAccount");

  // Alternatively, manually construct the transaction
  const recentBlockhash = await connection.getLatestBlockhash();
  const manualTransaction = new Transaction({
    recentBlockhash: recentBlockhash.blockhash,
    feePayer: payer,
  });
  manualTransaction.add(
    web3.SystemProgram.transfer({
      fromPubkey: payer,
      toPubkey: toAccount.publicKey,
      lamports: 1,
    })
  );

  const serialise = manualTransaction.serialize({
    verifySignatures: false,
    requireAllSignatures: false,
  });
  const signature = await sdk.getSolanaSDK().signTransaction(accounts[0], {
    unsigned_tx: serialise.toString('base64'),
    network: 'devnet',
  });
  const hash = await connection.sendRawTransaction(signature.signed_tx);
  console.log(hash);
};
```

### Conclusion

You have successfully created a Solana transaction, signed it using the MoonSDK, and sent it to the Solana network. You can now use the MoonSDK to interact with other blockchain networks and services as well.


# Bitcoin

Sure, here's a basic guide on how to interact with the Bitcoin blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List Bitcoin Accounts

To list Bitcoin accounts:

```javascript
async function listBitcoinAccounts() {
  try {
    const response = await moonSDK.getBitcoinSDK().listBitcoinAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listBitcoinAccounts();
```

### Create a Bitcoin Account

To create a new Bitcoin account:

```javascript
async function createBitcoinAccount() {
  try {
    const response = await moonSDK.getBitcoinSDK().createBitcoinAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createBitcoinAccount();
```

The `createBitcoinAccount` function will return an object containing the address and private key of the newly created account.

### Sign a Bitcoin Transaction

To sign a Bitcoin transaction:

```javascript
async function signBitcoinTransaction(accountName, toAddress, amount) {
  try {
    const response = await moonSDK.getBitcoinSDK().signBitcoinTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAddress,
      value: amount,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signBitcoinTransaction('your-account-name', 'recipient-address', 0.001);
```

Replace `'your-account-name'`, `'recipient-address'`, and `0.001` with the appropriate values. The `signBitcoinTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `bitcoinjs-lib` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.


# Bitcoin cash

Sure, here's a basic guide on how to interact with the Bitcoin Cash blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List Bitcoin Cash Accounts

To list Bitcoin Cash accounts:

```javascript
async function listBitcoinCashAccounts() {
  try {
    const response = await moonSDK.getBitcoincashSDK().listBitcoinCashAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listBitcoinCashAccounts();
```

### Create a Bitcoin Cash Account

To create a new Bitcoin Cash account:

```javascript
async function createBitcoinCashAccount() {
  try {
    const response = await moonSDK.getBitcoincashSDK().createBitcoinCashAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createBitcoinCashAccount();
```

The `createBitcoinCashAccount` function will return an object containing the address and private key of the newly created account.

### Sign a Bitcoin Cash Transaction

To sign a Bitcoin Cash transaction:

```javascript
async function signBitcoinCashTransaction(accountName, toAddress, amount) {
  try {
    const response = await moonSDK.getBitcoincashSDK().signBitcoinCashTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAddress,
      value: amount,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signBitcoinCashTransaction('your-account-name', 'recipient-address', 0.001);
```

Replace `'your-account-name'`, `'recipient-address'`, and `0.001` with the appropriate values. The `signBitcoinCashTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `bitcoincashjs-lib` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.


# Litecoin

Sure, here's a basic guide on how to interact with the Litecoin blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List Litecoin Accounts

To list Litecoin accounts:

```javascript
async function listLitecoinAccounts() {
  try {
    const response = await moonSDK.getLitecoinSDK().listLitecoinAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listLitecoinAccounts();
```

### Create a Litecoin Account

To create a new Litecoin account:

```javascript
async function createLitecoinAccount() {
  try {
    const response = await moonSDK.getLitecoinSDK().createLitecoinAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createLitecoinAccount();
```

The `createLitecoinAccount` function will return an object containing the address and private key of the newly created account.

### Sign a Litecoin Transaction

To sign a Litecoin transaction:

```javascript
async function signLitecoinTransaction(accountName, toAddress, amount) {
  try {
    const response = await moonSDK.getLitecoinSDK().signLitecoinTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAddress,
      value: amount,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signLitecoinTransaction('your-account-name', 'recipient-address', 0.001);
```

Replace `'your-account-name'`, `'recipient-address'`, and `0.001` with the appropriate values. The `signLitecoinTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `bitcoincashjs-lib` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.


# Dogecoin

Sure, here's a basic guide on how to interact with the Dogecoin blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List Dogecoin Accounts

To list Dogecoin accounts:

```javascript
async function listDogeCoinAccounts() {
  try {
    const response = await moonSDK.getDogecoinSDK().listDogeCoinAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listDogeCoinAccounts();
```

### Create a Dogecoin Account

To create a new Dogecoin account:

```javascript
async function createDogeCoinAccount() {
  try {
    const response = await moonSDK.getDogecoinSDK().createDogeCoinAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createDogeCoinAccount();
```

The `createDogeCoinAccount` function will return an object containing the address and private key of the newly created account.

### Sign a Dogecoin Transaction

To sign a Dogecoin transaction:

```javascript
async function signDogeCoinTransaction(accountName, toAddress, amount) {
  try {
    const response = await moonSDK.getDogecoinSDK().signDogeCoinTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAddress,
      value: amount,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signDogeCoinTransaction('your-account-name', 'recipient-address', 1);
```

Replace `'your-account-name'`, `'recipient-address'`, and `1` with the appropriate values. The `signDogeCoinTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `dogecoinjs-lib` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.
* Dogecoin uses a different unit of account than Bitcoin. One Dogecoin is equal to 100,000,000 Dogecoin coins, so you'll need to specify the amount in Dogecoin coins when sending a transaction.


# EOS

Sure, here's a basic guide on how to interact with the EOS blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List EOS Accounts

To list EOS accounts:

```javascript
async function listEosAccounts() {
  try {
    const response = await moonSDK.getEosSDK().listEosAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listEosAccounts();
```

### Create an EOS Account

To create a new EOS account:

```javascript
async function createEosAccount() {
  try {
    const response = await moonSDK.getEosSDK().createEosAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createEosAccount();
```

The `createEosAccount` function will return an object containing the account name and private key of the newly created account.

### Sign an EOS Transaction

To sign an EOS transaction:

```javascript
async function signEosTransaction(accountName, toAccount, quantity, symbol) {
  try {
    const response = await moonSDK.getEosSDK().signEosTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAccount,
      quantity: quantity,
      symbol: symbol,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signEosTransaction('your-account-name', 'recipient-account', '1.0000', 'EOS');
```

Replace `'your-account-name'`, `'recipient-account'`, `'1.0000'`, and `'EOS'` with the appropriate values. The `signEosTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `eosjs` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.
* EOS uses a different unit of account than Bitcoin. One EOS is equal to 1 EOS token, so you'll need to specify the amount in EOS tokens when sending a transaction.


# Ripple

Sure, here's a basic guide on how to interact with the Ripple blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List Ripple Accounts

To list Ripple accounts:

```javascript
async function listRippleAccounts() {
  try {
    const response = await moonSDK.getRippleSDK().listRippleAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listRippleAccounts();
```

### Create a Ripple Account

To create a new Ripple account:

```javascript
async function createRippleAccount() {
  try {
    const response = await moonSDK.getRippleSDK().createRippleAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createRippleAccount();
```

The `createRippleAccount` function will return an object containing the account name and private key of the newly created account.

### Sign a Ripple Transaction

To sign a Ripple transaction:

```javascript
async function signRippleTransaction(accountName, toAddress, amount, currency) {
  try {
    const response = await moonSDK.getRippleSDK().signRippleTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAddress,
      amount: amount,
      currency: currency,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signRippleTransaction('your-account-name', 'recipient-address', '100', 'XRP');
```

Replace `'your-account-name'`, `'recipient-address'`, `'100'`, and `'XRP'` with the appropriate values. The `signRippleTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `ripple-lib` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.
* Ripple uses a different unit of account than Bitcoin. One XRP is equal to 1,000,000 XRP drops, so you'll need to specify the amount in XRP drops when sending a transaction.


# Tron

Sure, here's a basic guide on how to interact with the Tron blockchain using the Moon SDK in Markdown format.

### Initialization

Firstly, you need to import the necessary modules and initialize the MoonSDK:

```javascript
import { MoonSDK } from '@moonup/moon-api';

const moonSDK = new MoonSDK({
  apiKey: 'your-api-key',
});
```

Replace `'your-api-key'` with your actual API key.

### List Tron Accounts

To list Tron accounts:

```javascript
async function listTronAccounts() {
  try {
    const response = await moonSDK.getTronSDK().listTronAccounts();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

listTronAccounts();
```

### Create a Tron Account

To create a new Tron account:

```javascript
async function createTronAccount() {
  try {
    const response = await moonSDK.getTronSDK().createTronAccount({
      network: 'testnet', // or 'mainnet'
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

createTronAccount();
```

The `createTronAccount` function will return an object containing the account name and private key of the newly created account.

### Sign a Tron Transaction

To sign a Tron transaction:

```javascript
async function signTronTransaction(accountName, toAddress, amount) {
  try {
    const response = await moonSDK.getTronSDK().signTronTransaction(accountName, {
      network: 'testnet', // or 'mainnet'
      to: toAddress,
      amount: amount,
    });
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

signTronTransaction('your-account-name', 'recipient-address', 100);
```

Replace `'your-account-name'`, `'recipient-address'`, and `100` with the appropriate values. The `signTronTransaction` function will return an object containing the signed transaction (`signedTx`) and the transaction hash (`transaction_hash`).

### Extra Notes

* Always remember to handle errors properly in your production code.
* This guide assumes that you're running in a Node.js environment. If you're running in a browser, you'll need to use a library like `tronweb` to sign transactions, as the browser doesn't have access to the file system to store private keys.
* This guide uses the testnet network for demonstration purposes. When you're ready to use the mainnet, make sure to change the `network` parameter to `'mainnet'`.
* Tron uses a different unit of account than Bitcoin. One TRX is equal to 1,000,000 TRX drops, so you'll need to specify the amount in TRX drops when sending a transaction.


# AI

## Moon and AI: Enhancing Blockchain Interactions with Artificial Intelligence

Moon is a comprehensive library that provides a set of APIs for interacting with various blockchain networks and decentralized finance (DeFi) protocols. By integrating Moon with AI, you can build applications that leverage the power of artificial intelligence to enhance blockchain interactions and provide new capabilities.

### How Moon and AI Work Together

Moon provides a wide range of APIs for interacting with various blockchain networks and DeFi protocols. These APIs allow you to perform tasks such as managing blockchain accounts, transferring tokens, and interacting with DeFi protocols.

AI, on the other hand, can be used to analyze data, make predictions, and automate tasks. By integrating Moon with AI, you can build applications that leverage the power of AI to enhance blockchain interactions and provide new capabilities.

For example, you can use AI to analyze blockchain data to identify trends, predict prices, and make investment decisions. You can also use AI to automate tasks such as managing blockchain accounts, transferring tokens, and interacting with DeFi protocols.

### Benefits of Using Moon with AI

There are several benefits to using Moon with AI:

1. **Enhanced blockchain interactions:** AI can be used to analyze data, make predictions, and automate tasks, which can enhance blockchain interactions and provide new capabilities.
2. **Improved decision-making:** By analyzing blockchain data, AI can help you make better decisions about investments, transactions, and other blockchain-related activities.
3. **Increased efficiency:** AI can be used to automate tasks, which can increase efficiency and reduce manual effort.
4. **New capabilities:** By integrating Moon with AI, you can build applications that provide new capabilities, such as predictive analytics, automated trading, and more.

### Getting Started with Moon and AI

To get started with Moon and AI, you'll need to have a basic understanding of blockchain and AI. You'll also need to install the necessary dependencies, such as Moon and an llm framework such as langchain

```typescript
import { ChatOpenAI } from '@langchain/openai';
import { createOpenAPIChain } from 'langchain/chains';

// Initialize the chat model using OpenAI's GPT-4
const chatModel = new ChatOpenAI({
  modelName: 'gpt-4-1106-preview',
  temperature: 0,
  openAIApiKey: process.env.OPENAI_API_KEY,
});

// Create an OpenAPI chain using the Moon API OpenAPI specification
const chain = await createOpenAPIChain('https://beta.usemoon.ai/.well-known/swagger.json', {
  llm: chatModel,
  headers: {
    'X-API-KEY': process.env.MOON_API_KEY,
  },
});

// Run a message through the chain and log the result
const message = 'Create a new Ethereum account';
const result = await chain.run(message);
console.log(JSON.stringify(result, null, 2));
```


# Langchain

## Langchain Documentation: Integrating with Moon API

The `langchain` library is a powerful tool for building applications that leverage language models to perform tasks such as text generation, summarization, and question answering. One of the ways to enhance the capabilities of a language model is to integrate it with external APIs that provide additional data or functionality. The `createOpenAPIChain` function in `langchain` allows you to easily integrate with an API that is described by an OpenAPI specification.

In this documentation page, we will show you how to use the `createOpenAPIChain` function to integrate with the OpenAPI specification provided by Moon API. Moon API is a comprehensive library that provides a set of APIs for interacting with various blockchain networks and decentralized finance (DeFi) protocols. By integrating with Moon API, you can build applications that leverage language models to perform tasks such as managing blockchain accounts, interacting with DeFi protocols, and more.

### Installation

To use the `createOpenAPIChain` function, you will need to install the `langchain` and `@langchain/openai` packages. You can install these packages using npm, Yarn, or pnpm:

{% tabs %}
{% tab title="npm" %}

```bash
npm install -S langchain @langchain/openai
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add langchain @langchain/openai
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add langchain @langchain/openai
```

{% endtab %}
{% endtabs %}

### Usage

Here is an example of how to use the `createOpenAPIChain` function to integrate with the OpenAPI specification provided by Moon API:

```javascript
import { ChatOpenAI } from '@langchain/openai';
import { createOpenAPIChain } from 'langchain/chains';

// Initialize the chat model using OpenAI's GPT-4
const chatModel = new ChatOpenAI({
  modelName: 'gpt-4-1106-preview',
  temperature: 0,
  openAIApiKey: process.env.OPENAI_API_KEY,
});

// Create an OpenAPI chain using the Moon API OpenAPI specification
const chain = await createOpenAPIChain('https://beta.usemoon.ai/.well-known/swagger.json', {
  llm: chatModel,
  headers: {
    Authorization: `Bearer ${MOON_API_KEY}`,
  },
});

// Run a message through the chain and log the result
const message = 'Create a new Ethereum account';
const result = await chain.run(message);
console.log(JSON.stringify(result, null, 2));
```

In this example, we first import the `ChatOpenAI` class from `@langchain/openai` and the `createOpenAPIChain` function from `langchain/chains`. We then initialize a chat model using OpenAI's GPT-4 and create an OpenAPI chain using the Moon API OpenAPI specification. We pass the chat model and an authorization header to the `createOpenAPIChain` function.

We then define a message that we want to run through the chain, which in this case is 'Create a new Ethereum account'. We call the `run` method on the chain with the message as an argument, which sends the message to the chat model and the OpenAPI chain, and returns the result. We log the result to the console.

The `createOpenAPIChain` function automatically generates a prompt that describes the API endpoints and their input and output schemas, and uses the chat model to generate a request that matches the API specification. The function then sends the request to the API and returns the response.

By integrating with Moon API using the `createOpenAPIChain` function, you can build applications that leverage language models to perform a wide range of tasks related to blockchain networks and DeFi protocols. Whether you're building a simple wallet application or a complex decentralized finance platform, Moon API and `langchain` have the tools you need to get the job done.

### Swagger Definitions

We chunk the swagger definition into route-

* [Swagger](https://beta.usemoon.ai/.well-known/swagger.json)
* [Accounts](https://beta.usemoon.ai/.well-known/Accounts.json)
* [Aave](https://beta.usemoon.ai/.well-known/Aave.json)
* [AI Plugin](https://beta.usemoon.ai/.well-known/ai-plugin.json)
* [Bitcoin Cash](https://beta.usemoon.ai/.well-known/bitcoincash.json)
* [Bitcoin](https://beta.usemoon.ai/.well-known/Bitcoin.json)
* [Conveyor Finance](https://beta.usemoon.ai/.well-known/ConveyorFinance.json)
* [Cosmos](https://beta.usemoon.ai/.well-known/Cosmos.json)
* [DogeCoin](https://beta.usemoon.ai/.well-known/DogeCoin.json)
* [ENS](https://beta.usemoon.ai/.well-known/ENS.json)
* [EOS](https://beta.usemoon.ai/.well-known/eos.json)
* [ERC1155](https://beta.usemoon.ai/.well-known/ERC1155.json)
* [ERC20](https://beta.usemoon.ai/.well-known/Erc20.json)
* [ERC4337](https://beta.usemoon.ai/.well-known/Erc4337.json)
* [ERC721](https://beta.usemoon.ai/.well-known/Erc721.json)
* [Litecoin](https://beta.usemoon.ai/.well-known/Litecoin.json)
* [1inch](https://beta.usemoon.ai/.well-known/oneinch.json)
* [Onramper](https://beta.usemoon.ai/.well-known/onramper.json)
* [OpenAPI](https://beta.usemoon.ai/.well-known/openapi.json)
* [Payment](https://beta.usemoon.ai/.well-known/payment.json)
* [Ripple](https://beta.usemoon.ai/.well-known/ripple.json)
* [Solana](https://beta.usemoon.ai/.well-known/Solana.json)
* [Tron](https://beta.usemoon.ai/.well-known/Tron.json)
* [UniSwap](https://beta.usemoon.ai/.well-known/UniSwap.json)
* [Yearn](https://beta.usemoon.ai/.well-known/yearn.json)


# Whisper

### Summary

The `langchain` library is a powerful tool for building applications that leverage language models to perform tasks such as text generation, summarization, and question answering. One of the ways to enhance the capabilities of a language model is to integrate it with external APIs that provide additional data or functionality. The `createOpenAPIChain` function in `langchain` allows you to easily integrate with an API that is described by an OpenAPI specification.

In this documentation page, we will show you how to use the `useWhisper` function from the `@chengsokdara/use-whisper` package to integrate with the OpenAPI specification provided by Moon API. Moon API is a comprehensive library that provides a set of APIs for interacting with various blockchain networks and decentralized finance (DeFi) protocols. By integrating with Moon API using Whisper, you can build applications that leverage audio input to perform tasks such as managing blockchain accounts, interacting with DeFi protocols, and more.

### Installation

{% tabs %}
{% tab title="npm" %}

```bash
npm install -S langchain @langchain/openai @chengsokdara/use-whisper
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add langchain @langchain/openai @chengsokdara/use-whisper
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add langchain @langchain/openai @chengsokdara/use-whisper
```

{% endtab %}
{% endtabs %}

### Usage

Here is an example of how to use the `useWhisper` function to integrate with the OpenAPI specification provided by Moon API:

```typescript
import { ChatOpenAI } from '@langchain/openai';
import { createOpenAPIChain } from 'langchain/chains';
import { useWhisper } from '@chengsokdara/use-whisper';
import { useEffect, useState } from 'react';

function Whisper() {
  const [chain, setChain] = useState<any>(null);
  const [results, setResults] = useState<any[]>([]);
  const {
    recording,
    speaking,
    transcribing,
    transcript,
    pauseRecording,
    startRecording,
    stopRecording,
  } = useWhisper({
    apiKey: process.env.REACT_APP_OPENAI_API_KEY
  });

  useEffect(() => {
    const initializeChat = async () => {
      const chatModel = new ChatOpenAI({
        modelName: 'gpt-4-1106-preview',
        temperature: 0,
        openAIApiKey: process.env.OPENAI_API_KEY,
      });
      const chain = await createOpenAPIChain('https://beta.usemoon.ai/.well-known/swagger.json', {
        llm: chatModel,
        headers: {
          Authorization: `Bearer ${MOON_API_KEY}`,
        },
      });
      setChain(chain);
    };
    initializeChat();
  }, []);

  const sendMessage = async () => {
    if (chain) {
      const result = await chain.run(transcript.text);
      console.log(JSON.stringify(result, null, 2));
      setResults((prevResults) => [...prevResults, result]);
    }
  };

  return (
    <div>
      <p>Recording: {recording}</p>
      <p>Speaking: {speaking}</p>
      <p>Transcribing: {transcribing}</p>
      <p>Transcribed Text: {transcript.text}</p>
      <button onClick={() => startRecording()}>Start</button>
      <button onClick={() => pauseRecording()}>Pause</button>
      <button onClick={() => stopRecording()}>Stop</button>
      <button onClick={sendMessage}>Send</button>
      {results.map((result, index) => (
        <p key={index}>{JSON.stringify(result)}</p>
      ))}
    </div>
  );
}

export default Whisper;




```

In this example, we first import the `ChatOpenAI` class from `@langchain/openai`, the `createOpenAPIChain` function from `langchain/chains`, and the `useWhisper` function from `@chengsokdara/use-whisper`. We then define a functional component `Whisper` that uses the `useWhisper` hook to handle audio recording and transcription.

We initialize a chat model using OpenAI's GPT-4 and create an OpenAPI chain using the Moon API OpenAPI specification in the `useEffect` hook. We then define a `sendMessage` function that sends the transcribed text to the Moon API and displays the results.

The component renders the recording, speaking, and transcribing status, the transcribed text, and buttons to start, pause, and stop recording, as well as a button to send the transcribed text to the Moon API. The results are displayed below the buttons.

By integrating with Moon API using the `useWhisper` function, you can build applications that leverage audio input to perform a wide range of tasks related to blockchain networks and DeFi protocols. Whether you're building a simple wallet application or a complex decentralized finance platform, Moon API and `langchain` have the tools you need to get the job done.


# Chat GPT

### Summary

The Moon Wallet ChatGPT Plugin integrates the powerful capabilities of the Moon Wallet infrastructure with the AI-driven functionality of ChatGPT. This plugin enables seamless interactions with blockchain wallets, providing users with a wide range of services including wallet creation, transaction signing, authentication, and more. Below, we outline the features, installation, configuration, and usage of the Moon Wallet ChatGPT Plugin.

### Usage

You can search for the moon wallet plugin on the gpt store

<figure><img src="/files/JQYAuIq9MHH0GbZJ6N8N" alt=""><figcaption></figcaption></figure>

You can also access the moon wallet chatgpt plugin directly at

<https://chatgpt.com/g/g-1Ou9DoNMd-moon-wallet>


# Moon Packages

Moon has a collection of packages and tools that can be used to build and customize a user interface for a wallet that interacts with various blockchains, including Ethereum. To help with this, we recommend using the following packages from the `@moonup` organization:

\
`@moonup/moon-sdk`: This is the core package of Moon, which handles authentication and initialization. It provides a convenient way to integrate Moon's services into your application.

[@moonup/moon-sdk](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-sdk)

`@moonup/moon-api`: This is a low-level API package that provides access to Moon's services. It allows you to interact with Moon's services programmatically.

[@moonup/moon-api](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api)

`@moonup/ethers`: This package provides a smooth interface for interacting with the Ethereum blockchain. It is built on top of the `ethers.js` library and provides additional functionality for working with Moon's services.

[@moonup/ethers](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-ethers-f381fbf881c647e1aab3d43fb4ad0600)

`@moonup/wagmi-connector`: This package provides a WAGMI connector for Moon, which makes it easier to integrate Moon's services into React-based dApps. It allows you to connect to Moon's services and interact with them using the WAGMI library.

[@moonup/wagmi-connector](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-wagmi-3d44fd4699594c2397129482dc52589f)

`@moonup/viem`: This package provides a Moon connector for Viem, which is a modern Ethereum library. It allows you to connect to Moon's services and interact with them using the Viem library.

[@moonup/viem](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-viem)

`@moonup/moon-rainbowkit`: This package provides a Moon connector for RainbowKit, which is a popular library for building wallet connections in React-based dApps. It allows you to use Moon's services for authentication and wallet management in your RainbowKit-based dApp.

[@moonup/moon-rainbowkit](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-rainbowkit)

`@moonup/moon-react`: This package provides a collection of React components that can be used to build a user interface for a Moon-based wallet. It includes components for displaying account balances, transaction history, and more.

[@moonup/moon-react](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-react)

These packages can be used individually or in combination to build a customized user interface for a Moon-based wallet that meets your specific needs. They provide a range of functionality for interacting with Moon's services and the Ethereum blockchain, and can be integrated into a variety of React-based dApps using popular libraries such as WAGMI, Viem, and RainbowKit.


# @moonup/moon-sdk

## @moonup/moon-sdk Package Documentation

## **About Moon SDK:**

The @moonup/moon-sdk package is a comprehensive SDK that provides easy access to various blockchain functionalities. It supports multiple chains such as Ethereum, Solana, Bitcoin, Cosmos, EOS, Litecoin, Ripple, Tron, Bitcoincash, and Dogecoin. The SDK includes functionalities for managing accounts, interacting with DeFi protocols like Aave, Uniswap, and Yearn, and working with NFTs (ERC-20, ERC-721, and ERC-1155).

## **Installing Moon SDK:**

To utilize the Moon SDK package, first install it to the desired directory of the project:

#### To install Moon SDK:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/moon-sdk
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/moon-sdk
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/moon-sdk
```

{% endtab %}
{% endtabs %}

### Usage

Here's a basic example of how to use the SDK:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const moonSDK = new MoonSDK({ apiKey: 'your-api-key' });

// List accounts
const accounts = await moonSDK.listAccounts();
console.log(accounts);

// Create a new account
const newAccount = await moonSDK.createAccount();
console.log(newAccount);

// Sign a transaction
const signedTx = await moonSDK.SignTransaction(wallet, transaction);
console.log(signedTx);

// Broadcast a transaction
const txHash = await moonSDK.SendTransaction(wallet, signedTx, chain_id);
console.log(txHash);
```

### Events

The MoonSDK class emits various events that you can listen to in order to handle specific actions or errors. Here's an example of how to listen to events:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const moonSDK = new MoonSDK();

moonSDK.on('accountCreated', (account) => {
  console.log(`Account created: ${account}`);
});

moonSDK.on('transactionSigned', (signedTransaction) => {
  console.log(`Transaction signed: ${signedTransaction}`);
});

moonSDK.on('messageSigned', (signedMessage) => {
  console.log(`Message signed: ${signedMessage}`);
});

moonSDK.on('typedDataSigned', (signedTypedData) => {
  console.log(`Typed data signed: ${signedTypedData}`);
});

moonSDK.on('transactionSent', (transactionHash) => {
  console.log(`Transaction sent: ${transactionHash}`);
});

moonSDK.on('chainsFetched', (chains) => {
  console.log(`Chains fetched: ${JSON.stringify(chains)}`);
});

moonSDK.on('chainFetched', (chain) => {
  console.log(`Chain fetched: ${JSON.stringify(chain)}`);
});

moonSDK.on('error', (error) => {
  console.error(`An error occurred: ${error.message}`);
});
```

The available events are:

* `accountCreated`: Emitted when a new account is created.
* `transactionSigned`: Emitted when a transaction is signed.
* `messageSigned`: Emitted when a message is signed.
* `typedDataSigned`: Emitted when typed data is signed.
* `transactionSent`: Emitted when a transaction is sent.
* `chainsFetched`: Emitted when the list of supported chains is fetched.
* `chainFetched`: Emitted when a specific chain is fetched.
* `error`: Emitted when an error occurs.

### API Reference

#### MoonSDK Class

**Constructor**

```javascript
new MoonSDK(config?: MoonSDKConfig)
```

* `config` (optional): Configuration object for the SDK.
  * `apiKey` (string): Your API key for authentication.
  * `authInstance` (SupabaseClient): An existing Supabase client instance for authentication.
  * `httpParams` (ApiConfig): Configuration for the HTTP client.
  * `httpInstance` (HttpClient): An existing HttpClient instance.
  * clientId (string): Moon oauth2 client id param

**Methods**

* `connect(accessToken?: string, refreshToken?: string)`: Establishes a connection to the Moon API.

  ```javascript
  await moonSDK.connect('access-token', 'refresh-token');
  ```
* `disconnect()`: Disconnects from the Moon API.

  ```javascript
  await moonSDK.disconnect();
  ```
* `getMoonAuth()`: Returns the Supabase client instance for authentication.

  ```javascript
  const authClient = moonSDK.getMoonAuth();
  ```
* `getUserSession()`: Returns the current user session.

  ```javascript
  const session = await moonSDK.getUserSession();
  ```
* `getSolanaSDK()`: Returns the Solana SDK instance.

  ```javascript
  const solanaSDK = moonSDK.getSolanaSDK();
  ```
* `getBitcoinSDK()`: Returns the Bitcoin SDK instance.

  ```javascript
  const bitcoinSDK = moonSDK.getBitcoinSDK();
  ```
* `getCosmosSDK()`: Returns the Cosmos SDK instance.

  ```javascript
  const cosmosSDK = moonSDK.getCosmosSDK();
  ```
* `getEosSDK()`: Returns the EOS SDK instance.

  ```javascript
  const eosSDK = moonSDK.getEosSDK();
  ```
* `getLitecoinSDK()`: Returns the Litecoin SDK instance.

  ```javascript
  const litecoinSDK = moonSDK.getLitecoinSDK();
  ```
* `getRippleSDK()`: Returns the Ripple SDK instance.

  ```javascript
  const rippleSDK = moonSDK.getRippleSDK();
  ```
* `getTronSDK()`: Returns the Tron SDK instance.

  ```javascript
  const tronSDK = moonSDK.getTronSDK();
  ```
* `getBitcoincashSDK()`: Returns the Bitcoincash SDK instance.

  ```javascript
  const bitcoincashSDK = moonSDK.getBitcoincashSDK();
  ```
* `getDogecoinSDK()`: Returns the Dogecoin SDK instance.

  ```javascript
  const dogecoinSDK = moonSDK.getDogecoinSDK();
  ```
* `getAccountsSDK()`: Returns the Accounts SDK instance.

  ```javascript
  const accountsSDK = moonSDK.getAccountsSDK();
  ```
* `getAaveSDK()`: Returns the Aave SDK instance.

  ```javascript
  const aaveSDK = moonSDK.getAaveSDK();
  ```
* `getConveyorfinanceSDK()`: Returns the Conveyorfinance SDK instance.

  ```javascript
  const conveyorfinanceSDK = moonSDK.getConveyorfinanceSDK();
  ```
* `getENSSDK()`: Returns the ENS SDK instance.

  ```javascript
  const ensSDK = moonSDK.getENSSDK();
  ```
* `getErc20SDK()`: Returns the ERC-20 SDK instance.

  ```javascript
  const erc20SDK = moonSDK.getErc20SDK();
  ```
* `getErc1155SDK()`: Returns the ERC-1155 SDK instance.

  ```javascript
  const erc1155SDK = moonSDK.getErc1155SDK();
  ```
* `getErc721SDK()`: Returns the ERC-721 SDK instance.

  ```javascript
  const erc721SDK = moonSDK.getErc721SDK();
  ```
* `getOneinchSDK()`: Returns the 1inch SDK instance.

  ```javascript
  const oneinchSDK = moonSDK.getOneinchSDK();
  ```
* `getUniswapSDK()`: Returns the Uniswap SDK instance.

  ```javascript
  const uniswapSDK = moonSDK.getUniswapSDK();
  ```
* `getYearnSDK()`: Returns the Yearn SDK instance.

  ```javascript
  const yearnSDK = moonSDK.getYearnSDK();
  ```
* `listAccounts()`: Lists all available accounts.

  ```javascript
  const accounts = await moonSDK.listAccounts();
  ```
* `createAccount()`: Creates a new account.

  ```javascript
  const newAccount = await moonSDK.createAccount();
  ```
* `SignTransaction(wallet: string, transaction: InputBody)`: Signs a transaction.

  ```javascript
  const signedTx = await moonSDK.SignTransaction(wallet, transaction);
  ```
* `SignMessage(wallet: string, message: BytesLike)`: Signs a message.

  ```javascript
  const signedMessage = await moonSDK.SignMessage(wallet, message);
  ```
* `SignTypedData(wallet: string, domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, string>)`: Signs typed data.

  ```javascript
  const signedTypedData = await moonSDK.SignTypedData(wallet, domain, types, value);
  ```
* `SendTransaction(wallet: string, rawTransaction: string, chain_id: string)`: Broadcasts a transaction.

  ```javascript
  const txHash = await moonSDK.SendTransaction(wallet, signedTx, chain_id);
  ```
* `getChains()`: Retrieves a list of supported chains.

  ```javascript
  const chains = await moonSDK.getChains();
  ```
* `getChainById(id: string)`: Retrieves a chain by its ID.

  ```javascript
  const chain = await moonSDK.getChainById('chain-id');
  ```

### Authentication Methods

The Moon SDK supports various authentication methods to provide secure access to the blockchain functionalities. The following authentication methods are available:

### Usage

Here's a basic example of how to use the SDK:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';

const moonSDK = new MoonSDK({ clientId: 'your-client-id' });

// Discord OAuth
await moonSDK.performDiscordOAuth();
// After obtaining the authorization code, exchange it for an access token and refresh token
const discordToken = await moonSDK.performDiscordOauthCodeExchange(code);

// GitHub OAuth
await moonSDK.performGithubOAuth();
// After obtaining the authorization code, exchange it for an access token and refresh token
const githubToken = await moonSDK.performGithubOauthCodeExchange(code);

// Google OAuth
await moonSDK.performGoogleOAuth();
// After obtaining the authorization code, exchange it for an access token and refresh token
const googleToken = await moonSDK.performGoogleOauthCodeExchange(code);

// Twitter OAuth
await moonSDK.performTwitterOauth();
// After obtaining the authorization code, exchange it for an access token and refresh token
const twitterToken = await moonSDK.performTwitterOauthCodeExchange(code);

// Magic Link
await moonSDK.sendMagicLink(email, redirectTo);

// Email and Password
await moonSDK.signUp(email, password);
await moonSDK.signInWithPassword(email, password);

// Phone and Password
await moonSDK.signInWithPhone(phone, password);

// Passkey
const passkeyOptions = await moonSDK.handlePassKeyLogin(email);
// Use the passkeyOptions to authenticate the user using their passkey
const passkeyResponse = await moonSDK.handlePasskeyLoginVerify(email, credential);

// SIWE (Sign-In with Ethereum)
const nonce = await moonSDK.getSIWENonce(address);
// Sign the SIWE message using the Ethereum wallet
const siweResponse = await moonSDK.verifySIWESignature(address, signedMessage, nonce, message);

// Embedded Account
const session = await moonSDK.embeddedAccount(email, uuid, domain);
```

#### Discord OAuth

To authenticate using Discord OAuth, follow these steps:

1. Initiate the Discord OAuth flow:

   ```javascript
   await moonSDK.performDiscordOAuth();
   ```
2. After the user is redirected to the Discord authorization page, obtain the authorization code from the URL.
3. Exchange the authorization code for an access token and refresh token:

   ```javascript
   const token = await moonSDK.performDiscordOauthCodeExchange(code);
   ```

#### GitHub OAuth

To authenticate using GitHub OAuth, follow these steps:

1. Initiate the GitHub OAuth flow:

   ```javascript
   await moonSDK.performGithubOAuth();
   ```
2. After the user is redirected to the GitHub authorization page, obtain the authorization code from the URL.
3. Exchange the authorization code for an access token and refresh token:

   ```javascript
   const token = await moonSDK.performGithubOauthCodeExchange(code);
   ```

#### Google OAuth

To authenticate using Google OAuth, follow these steps:

1. Initiate the Google OAuth flow:

   ```javascript
   await moonSDK.performGoogleOAuth();
   ```
2. After the user is redirected to the Google authorization page, obtain the authorization code from the URL.
3. Exchange the authorization code for an access token and refresh token:

   ```javascript
   const token = await moonSDK.performGoogleOauthCodeExchange(code);
   ```

#### Twitter OAuth

To authenticate using Twitter OAuth, follow these steps:

1. Initiate the Twitter OAuth flow:

   ```javascript
   await moonSDK.performTwitterOauth();
   ```
2. After the user is redirected to the Twitter authorization page, obtain the authorization code from the URL.
3. Exchange the authorization code for an access token and refresh token:

   ```javascript
   const token = await moonSDK.performTwitterOauthCodeExchange(code);
   ```

#### Magic Link

To authenticate using a magic link, follow these steps:

1. Send a magic link to the user's email address:

   ```javascript
   await moonSDK.sendMagicLink(email, redirectTo);
   ```
2. The user will receive an email with a magic link. After clicking the link, they will be redirected to the specified `redirectTo` URL.

#### Email and Password

To authenticate using email and password, follow these steps:

1. Create a new user account:

   ```javascript
   await moonSDK.signUp(email, password);
   ```
2. Sign in with the created account:

   ```javascript
   await moonSDK.signInWithPassword(email, password);
   ```

#### Phone and Password

To authenticate using phone and password, follow these steps:

1. Sign in with the phone number and password:

   ```javascript
   await moonSDK.signInWithPhone(phone, password);
   ```

#### Passkey

To authenticate using a passkey, follow these steps:

1. Initiate the passkey login flow:

   ```javascript
   const options = await moonSDK.handlePassKeyLogin(email);
   ```
2. Use the `options` to authenticate the user using their passkey.
3. Verify the passkey login credentials:

   ```javascript
   const response = await moonSDK.handlePasskeyLoginVerify(email, credential);
   ```

#### SIWE (Sign-In with Ethereum)

To authenticate using SIWE, follow these steps:

1. Retrieve a nonce for the Ethereum address:

   ```javascript
   const nonce = await moonSDK.getSIWENonce(address);
   ```
2. Sign the SIWE message using the Ethereum wallet.
3. Verify the SIWE signature:

   ```javascript
   const response = await moonSDK.verifySIWESignature(address, signedMessage, nonce, message);
   ```

#### Embedded Account

To create an embedded account, follow these steps:

1. Create an embedded account for the specified email address, UUID, and domain:

   ```javascript
   const session = await moonSDK.embeddedAccount(email, uuid, domain);
   ```


# @moonup/ethers

## @moonup/ethers Package Documentation

### Summary

The `@moonup/ethers` package is a utility package that provides a `MoonProvider` class and a `MoonSigner` class for interacting with Ethereum-based blockchains using the MoonSDK from the `@moonup/moon-sdk` package. The `MoonProvider` class implements the `Provider` and `IEthereumProvider` interfaces from the `ethers` library, while the `MoonSigner` class implements the `Signer` and `TypedDataSigner` interfaces from the `ethers` library.

### Setup

To use the `@moonup/ethers` package, you need to install it and import the `MoonProvider` and `MoonSigner` classes.

#### To install Moon Ethers:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/ethers
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/ethers
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/ethers
```

{% endtab %}
{% endtabs %}

#### Importing the classes

To import the `MoonProvider` and `MoonSigner` classes, you can use the following code:

```javascript
import { MoonProvider, MoonSigner } from '@moonup/ethers';
```

### Usage

#### MoonProvider

The `MoonProvider` class is a provider for interacting with Ethereum-based blockchains using the MoonSDK. It can be used to sign messages, transactions, and typed data using the MoonSDK, and it implements the `Provider` and `IEthereumProvider` interfaces from the `ethers` library.

To create a new instance of the `MoonProvider` class, you need to provide a configuration object that contains the following properties:

* `SDK` (MoonSDK): An instance of the MoonSDK.
* `address` (string): The Ethereum address of the account.
* `chainId` (number): The ID of the Ethereum chain.

Here's an example of how to create a new instance of the `MoonProvider` class:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { MoonProvider } from '@moonup/ethers';

const SDK = new MoonSDK({ /* your configuration */ });
const address = '0xYourEthereumAddress';
const chainId = 1; // mainnet

const provider = new MoonProvider({ SDK, address, chainId });
```

Documentation here:

[`MoonProvider`](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-ethers-f381fbf881c647e1aab3d43fb4ad0600/moonprovider-98424fc361554e529b42c6618739e9be)

#### MoonSigner

The `MoonSigner` class is a signer for signing messages, transactions, and typed data using the MoonSDK. It implements the `Signer` and `TypedDataSigner` interfaces from the `ethers` library.

To create a new instance of the `MoonSigner` class, you need to provide a configuration object that contains the following properties:

* `SDK` (MoonSDK): An instance of the MoonSDK.
* `address` (string): The Ethereum address of the account.
* `chainId` (number): The ID of the Ethereum chain.

Here's an example of how to create a new instance of the `MoonSigner` class:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { MoonSigner } from '@moonup/ethers';

const SDK = new MoonSDK({ /* your configuration */ });
const address = '0xYourEthereumAddress';
const chainId = 1; // mainnet

const signer = new MoonSigner({ SDK, address, chainId });
```

Documentation here:

[MoonSigner](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moon-ethers-f381fbf881c647e1aab3d43fb4ad0600/moonsigner-48c2980a33ab459b98198d189f18f641)

### Additional notes

* The `MoonProvider` class can be connected to a `MoonSigner` instance using the `getSigner` method.
* The `MoonSigner` class can be connected to a `MoonProvider` instance using the `connect` method.
* The `MoonProvider` class and the `MoonSigner` class can be used with other `ethers` classes and functions, such as `Contract`, `Wallet`, and `utils`.
* The `MoonProvider` class and the `MoonSigner` class are compatible with the Ethereum JSON-RPC API, which means that they can be used with other Ethereum clients and tools that support JSON-RPC.
* The `MoonProvider` class and the `MoonSigner` class are designed to be used with the MoonSDK, which is a software development kit for building decentralized applications on the Moonbeam and Moonriver networks. However, they can also be used with other Ethereum-based blockchains that support the Ethereum JSON-RPC API.


# MoonProvider

<br>

## @moonup/ethers Package Documentation

### Summary

The `@moonup/ethers` package is a utility package that provides a `MoonProvider` class for interacting with Ethereum-based blockchains using the MoonSDK from the `@moonup/moon-sdk` package. This provider can be used to sign messages, transactions, and typed data using the MoonSDK, and it implements the `Provider` and `IEthereumProvider` interfaces from the `ethers` library.

### Usage Examples

Here's a basic example of how to use the `MoonProvider` class:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { MoonProvider } from '@moonup/ethers';
import { ethers } from 'ethers';

const SDK = new MoonSDK({ /* your configuration */ });
const address = '0xYourEthereumAddress';
const chainId = 1; // mainnet

const provider = new MoonProvider({ SDK, address, chainId });

// Now you can use the provider with ethers
const signer = provider.getSigner();
const balance = await signer.getBalance();
console.log(`Balance: ${ethers.utils.formatEther(balance)} ETH`);
```

### API Reference

#### `MoonProvider`

A provider for interacting with Ethereum-based blockchains using the MoonSDK.

**Constructor**

* `options` (Object)
  * `SDK` (MoonSDK): An instance of the MoonSDK.
  * `address` (string): The Ethereum address of the account.
  * `chainId` (number): The ID of the Ethereum chain.

**Methods**

* `request(args: RequestArguments)`: Sends a JSON-RPC request.

  ```javascript
  const blockNumber = await provider.request({ method: 'eth_blockNumber' });
  console.log(`Current block number: ${blockNumber}`);
  ```
* `updateConfig(options: MoonProviderOptions)`: Updates the configuration options.

  ```javascript
  provider.updateConfig({ chainId: 4, address: '0xNewEthereumAddress' });
  ```
* `connect()`: Connects to the MoonSDK.

  ```javascript
  await provider.connect();
  ```
* `disconnect()`: Disconnects from the MoonSDK.

  ```javascript
  await provider.disconnect();
  ```
* `sendAsync(args: RequestArguments, callback: (error: Error | null, response: any) => void)`: Sends a JSON-RPC request asynchronously.

  ```javascript
  provider.sendAsync({ method: 'eth_blockNumber' }, (error, result) => {
    if (error) {
      console.error(error);
    } else {
      console.log(`Current block number: ${result}`);
    }
  });
  ```
* `enable()`: Enables the provider.

  ```javascript
  const accounts = await provider.enable();
  console.log(`Connected accounts: ${accounts}`);
  ```
* `isMoonProvider()`: Returns `true` if the provider is a `MoonProvider`.

  ```javascript
  console.log(`Is MoonProvider: ${provider.isMoonProvider()}`);
  ```
* `getChainId()`: Returns the ID of the Ethereum chain.

  ```javascript
  console.log(`Chain ID: ${provider.getChainId()}`);
  ```
* `getSigner()`: Returns the `MoonSigner` instance.

  ```javascript
  const signer = provider.getSigner();
  ```
* `getNetwork()`: Returns the network information.

  ```javascript
  const network = await provider.getNetwork();
  console.log(`Network name: ${network.name}`);
  ```
* `getBlockNumber()`: Returns the current block number.

  ```javascript
  const blockNumber = await provider.getBlockNumber();
  console.log(`Current block number: ${blockNumber}`);
  ```
* `getGasPrice()`: Returns the current gas price.

  ```javascript
  const gasPrice = await provider.getGasPrice();
  console.log(`Current gas price: ${gasPrice.toString()} wei`);
  ```
* `getBalance(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag> | undefined)`: Returns the balance of an account.

  ```javascript
  const balance = await provider.getBalance('0xYourEthereumAddress');
  console.log(`Balance: ${ethers.utils.formatEther(balance)} ETH`);
  ```
* `getTransactionCount(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag> | undefined)`: Returns the number of transactions sent from an account.

  ```javascript
  const transactionCount = await provider.getTransactionCount('0xYourEthereumAddress');
  console.log(`Transaction count: ${transactionCount}`);
  ```
* `getCode(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag> | undefined)`: Returns the code of a contract.

  ```javascript
  const code = await provider.getCode('0xYourContractAddress');
  console.log(`Contract code: ${code}`);
  ```
* `getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag> | undefined)`: Returns the value of a storage slot of a contract.

  ```javascript
  const storageValue = await provider.getStorageAt('0xYourContractAddress', 0);
  console.log(`Storage value: ${storageValue}`);
  ```
* `sendTransaction(signedTransaction: string | Promise<string>)`: Sends a transaction.

  ```javascript
  const signer = provider.getSigner();
  const transaction = {
    to: '0xRecipientAddress',
    value: ethers.utils.parseEther('1.0'),
  };
  const tx = await signer.sendTransaction(transaction);
  console.log(`Transaction hash: ${tx.hash}`);
  ```
* `call(transaction: Deferrable<TransactionRequest>, blockTag?: BlockTag | Promise<BlockTag> | undefined)`: Calls a contract method.

  ```javascript
  const contract = new ethers.Contract('0xYourContractAddress', abi, provider);
  const result = await contract.myMethod();
  console.log(`Method result: ${result}`);
  ```
* `estimateGas(transaction: Deferrable<TransactionRequest>)`: Estimates the gas required for a transaction.

  ```javascript
  const signer = provider.getSigner();
  const transaction = {
    to: '0xRecipientAddress',
    value: ethers.utils.parseEther('1.0'),
  };
  const gasLimit = await signer.estimateGas(transaction);
  console.log(`Estimated gas limit: ${gasLimit.toString()}`);
  ```
* `getBlock(blockHashOrBlockTag: BlockTag | Promise<BlockTag>)`: Returns a block.

  ```javascript
  const block = await provider.getBlock('latest');
  console.log(`Block number: ${block.number}`);
  ```
* `getBlockWithTransactions(blockHashOrBlockTag: BlockTag | Promise<BlockTag>)`: Returns a block with its transactions.

  ```javascript
  const block = await provider.getBlockWithTransactions('latest');
  console.log(`Block number: ${block.number}`);
  console.log(`Transactions: ${block.transactions.length}`);
  ```
* `getTransaction(transactionHash: string)`: Returns a transaction.

  ```javascript
  const transaction = await provider.getTransaction('0xYourTransactionHash');
  console.log(`Transaction hash: ${transaction.hash}`);
  ```
* `getTransactionReceipt(transactionHash: string)`: Returns a transaction receipt.

  ```javascript
  const receipt = await provider.getTransactionReceipt('0xYourTransactionHash');
  console.log(`Transaction status: ${receipt.status}`);
  ```
* `getLogs(filter: Filter)`: Returns logs that match a filter.

  ```javascript
  const filter = {
    address: '0xYourContractAddress',
    topics: [ethers.utils.id('MyEvent()')],
  };
  const logs = await provider.getLogs(filter);
  console.log(`Number of logs: ${logs.length}`);
  ```
* `resolveName(name: string | Promise<string>)`: Resolves an ENS name to an address.

  ```javascript
  const address = await provider.resolveName('myname.eth');
  console.log(`Address: ${address}`);
  ```
* `lookupAddress(address: string | Promise<string>)`: Resolves an address to an ENS name.

  ```javascript
  const name = await provider.lookupAddress('0xYourEthereumAddress');
  console.log(`Name: ${name}`);
  ```
* `emit(eventName: EventType, ...args: any[])`: Emits an event.

  ```javascript
  provider.on('block', (blockNumber) => {
    console.log(`New block: ${blockNumber}`);
  });
  provider.emit('block', 1234567);
  ```
* `listenerCount(eventName?: EventType | undefined)`: Returns the number of listeners for an event.

  ```javascript
  const listenerCount = provider.listenerCount('block');
  console.log(`Number of listeners: ${listenerCount}`);
  ```
* `listeners(eventName?: EventType | undefined)`: Returns the listeners for an event.

  ```javascript
  const listeners = provider.listeners('block');
  console.log(`Number of listeners: ${listeners.length}`);
  ```
* `removeAllListeners(eventName?: EventType | undefined)`: Removes all listeners for an event.

  ```javascript
  provider.removeAllListeners('block');
  ```
* `waitForTransaction(transactionHash: string, confirmations?: number | undefined, timeout?: number | undefined)`: Waits for a transaction to be mined.

  ```javascript
  const receipt = await provider.waitForTransaction('0xYourTransactionHash');
  console.log(`Transaction status: ${receipt.status}`);
  ```
* `on(eventName: EventType, listener: Listener)`: Adds a listener for an event.

  ```javascript
  provider.on('block', (blockNumber) => {
    console.log(`New block: ${blockNumber}`);
  });
  ```
* `once(eventName: EventType, listener: Listener)`: Adds a one-time listener for an event.

  ```javascript
  provider.once('block', (blockNumber) => {
    console.log(`New block: ${blockNumber}`);
  });
  ```
* `off(eventName: EventType, listener?: Listener | undefined)`: Removes a listener for an event.

  ```javascript
  const listener = (blockNumber) => {
    console.log(`New block: ${blockNumber}`);
  };
  provider.on('block', listener);
  provider.off('block', listener);
  ```

**Example**

```javascript
const provider = new MoonProvider({ SDK, address, chainId });
window.ethereum = moon;
```


# MoonSigner

### Summary

The `@moonup/ethers` package is a utility package that provides a `MoonSigner` class for signing messages, transactions, and typed data using the MoonSDK from the `@moonup/moon-sdk` package. This signer implements the `Signer` and `TypedDataSigner` interfaces from the `ethers` library.

### Usage Examples

Here's a basic example of how to use the `MoonSigner` class:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { MoonSigner } from '@moonup/ethers';
import { ethers } from 'ethers';

const SDK = new MoonSDK({ /* your configuration */ });
const address = '0xYourEthereumAddress';
const chainId = 1; // mainnet

const signer = new MoonSigner({ SDK, address, chainId });

// Now you can use the signer with ethers
const message = 'Hello, world!';
const signature = await signer.signMessage(message);
console.log(`Signature: ${signature}`);
```

### API Reference

#### `MoonSigner`

A signer for signing messages, transactions, and typed data using the MoonSDK.

**Constructor**

* `config` (Object)
  * `SDK` (MoonSDK): An instance of the MoonSDK.
  * `address` (string): The Ethereum address of the account.
  * `chainId` (number): The ID of the Ethereum chain.
* `provider` (Provider): An optional provider.

**Methods**

* `_signTypedData(domain: TypedDataDomain, types: Record<string, TypedDataField[]>, value: Record<string, any>)`: Signs a typed data object. This method is not implemented and throws an error.

  ```javascript
  // This method is not implemented and throws an error
  ```
* `updateConfig(config: MoonSignerConfig)`: Updates the configuration options.

  ```javascript
  signer.updateConfig({ chainId: 4, address: '0xNewEthereumAddress' });
  ```
* `connect(provider: Provider)`: Connects the signer to a provider.

  ```javascript
  const provider = new ethers.providers.JsonRpcProvider('https://rpc.example.com');
  const connectedSigner = signer.connect(provider);
  ```
* `signTypedData(domain: TypedDataDomain, types: Record<string, TypedDataField[]>, value: Record<string, string>)`: Signs a typed data object.

  ```javascript
  const domain = {
    name: 'MyDApp',
    version: '1',
    chainId: 1,
    verifyingContract: '0xYourContractAddress',
  };
  const types = {
    Person: [
      { name: 'name', type: 'string' },
      { name: 'age', type: 'uint256' },
    ],
  };
  const value = {
    name: 'John Doe',
    age: 30,
  };
  const signature = await signer.signTypedData(domain, types, value);
  console.log(`Signature: ${signature}`);
  ```
* `getAddress()`: Returns the Ethereum address of the account.

  ```javascript
  const address = await signer.getAddress();
  console.log(`Address: ${address}`);
  ```
* `signMessage(message: BytesLike)`: Signs a message.

  ```javascript
  const message = 'Hello, world!';
  const signature = await signer.signMessage(message);
  console.log(`Signature: ${signature}`);
  ```
* `broadcastTransaction(signedTransaction: string)`: Broadcasts a signed transaction.

  ```javascript
  const signedTransaction = '0xYourSignedTransaction';
  const transactionHash = await signer.broadcastTransaction(signedTransaction);
  console.log(`Transaction hash: ${transactionHash}`);
  ```
* `sendTransaction(transaction: TransactionRequest)`: Signs and broadcasts a transaction.

  ```javascript
  const transaction = {
    to: '0xRecipientAddress',
    value: ethers.utils.parseEther('1.0'),
  };
  const txResponse = await signer.sendTransaction(transaction);
  console.log(`Transaction hash: ${txResponse.hash}`);
  ```
* `transactionRequestToInputBody(tx: TransactionRequest)`: Converts a `TransactionRequest` object to an `InputBody` object.

  ```javascript
  const transaction = {
    to: '0xRecipientAddress',
    value: ethers.utils.parseEther('1.0'),
  };
  const inputBody = signer.transactionRequestToInputBody(transaction);
  console.log(`Input body: ${JSON.stringify(inputBody)}`);
  ```
* `moonTransactionResponseToTransactions(tx: MoonTransaction)`: Converts a `MoonTransaction` object to an array of `TransactionData` objects.

  ```javascript
  const moonTransaction = {
    transactions: [
      {
        hash: '0xYourTransactionHash',
        // ...
      },
    ],
  };
  const transactions = signer.moonTransactionResponseToTransactions(moonTransaction);
  console.log(`Transactions: ${JSON.stringify(transactions)}`);
  ```
* `signTransaction(transaction: TransactionRequest)`: Signs a transaction.

  ```javascript
  const transaction = {
    to: '0xRecipientAddress',
    value: ethers.utils.parseEther('1.0'),
  };
  const signedTransaction = await signer.signTransaction(transaction);
  console.log(`Signed transaction: ${signedTransaction}`);
  ```
* `getTypedDataDomain(name: string, version: string, chainId: number, verifyingContract: string)`: Returns a `TypedDataDomain` object.

  ```javascript
  const domain = await signer.getTypedDataDomain('MyDApp', '1', 1, '0xYourContractAddress');
  console.log(`Typed data domain: ${JSON.stringify(domain)}`);
  ```
* `getTypedData(domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, message: Record<string, string>)`: Returns a `Typed` object.

  ```javascript
  const domain = {
    name: 'MyDApp',
    version: '1',
    chainId: 1,
    verifyingContract: '0xYourContractAddress',
  };
  const types = {
    Person: [
      { name: 'name', type: 'string' },
      { name: 'age', type: 'uint256' },
    ],
  };
  const value = {
    name: 'John Doe',
    age: 30,
  };
  const typedData = await signer.getTypedData(domain, types, value);
  console.log(`Typed data: ${JSON.stringify(typedData)}`);
  ```

**Example**

```javascript
const signer = new MoonSigner({ SDK, address, chainId });
```


# @moonup/wagmi-connector

## @moonup/wagmi-connector Package Documentation

The `@moonup/wagmi-connector` package is a connector for the `wagmi` library that allows for the integration of the MoonSDK from the `@moonup/moon-sdk` package. This connector can be used to connect to a Moon wallet and interact with Ethereum-based blockchains.

## **Installing Moon Wagmi:**

To use the Moon Wagmi package, first install it to a project:

#### To install Moon Wagmi:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/wagmi-connector
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/wagmi-connector
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/wagmi-connector
```

{% endtab %}
{% endtabs %}

### Usage Examples

Here's a basic example of how to use the `createMoonConnector` function:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { createMoonConnector } from '@moonup/wagmi-connector';
import { WagmiConfig, createClient, configureChains } from 'wagmi';
import { publicProvider } from 'wagmi/providers/public';

const { chains, provider } = configureChains([chain], [publicProvider()]);

const SDK = new MoonSDK({ /* your configuration */ });
const address = '0xYourEthereumAddress';
const chainId = 1; // mainnet

const client = createClient({
  autoConnect: true,
  provider,
  connectors: [
    createMoonConnector({ SDK, address, chainId, chains }),
  ],
});

function App() {
  return (
    <WagmiConfig client={client}>
      {/* Your app components */}
    </WagmiConfig>
  );
}
```

### API Reference

#### `createMoonConnector`

Creates a connector for the `wagmi` library using the MoonSDK.

**Parameters**

* `options` (Object)
  * `SDK` (MoonSDK): An instance of the MoonSDK.
  * `address` (string): The Ethereum address of the account.
  * `chainId` (number): The ID of the Ethereum chain.
  * `chains` (Chain\[]): An array of Ethereum chains.

**Returns**

A `CreateConnectorFn` function that can be used to create a connector for the `wagmi` library.

**Example**

```javascript
const connector = createMoonConnector({ SDK, address, chainId, chains });
```


# @moonup/viem

## @moonup/viem Package Documentation

The `@moonup/viem` package is a utility package that allows for the creation of a local account using the MoonSDK from the `@moonup/moon-sdk` package. This local account can be used with the `viem` library for signing messages, transactions, and typed data.=

## **Installing Moon Viem:**

To utilize the Moon Viem package, first install it to the desired directory of the project:

#### To install Moon Viem:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/viem
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn install @moonup/viem
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/viem
```

{% endtab %}
{% endtabs %}

### Usage Examples

Here's a basic example of how to use the `createMoonAccount` function:

```javascript
import { MoonSDK } from '@moonup/moon-sdk';
import { createMoonAccount } from '@moonup/viem';

const sdk = new MoonSDK({ /* your configuration */ });
const ethereumAddress = '0xYourEthereumAddress';

const account = await createMoonAccount({ sdk, ethereumAddress });

// Now you can use the account with viem
```

### API Reference

#### `createMoonAccount`

Creates a local account using the MoonSDK.

**Parameters**

* `input` (Object)
  * `sdk` (MoonSDK): An instance of the MoonSDK.
  * `ethereumAddress` (string): The Ethereum address of the account.

**Returns**

A promise that resolves to a `LocalAccount` object.

**Example**

```javascript
const account = await createMoonAccount({ sdk, ethereumAddress });
```


# @moonup/moon-rainbowkit

## @moonup/moon-rainbowkit Package Documentatio&#x6E;**:**

The `@moonup/moon-rainbowkit` package is a React component that provides authentication functionality using the Moon SDK and RainbowKit. This package allows users to sign in with Ethereum to the app using SIWE (Sign-In with Ethereum) and manages the authentication state.

<br>

## **Installing Moon Rainbowkit:**

To utilize the Moon rainbowkit package, first install it to the desired directory of the project:

#### To install Moon rainbowkit

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/moon-rainbowkit
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/moon-rainbowkit
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/moon-rainbowkit
```

{% endtab %}
{% endtabs %}

### Usage

Import the `RainbowMoonProvider` component from the package and wrap your application with it.

```tsx
import {RainbowKitUseMoonProvider} from '@moonup/moon-rainbowkit';
import {
  RainbowKitProvider,
} from '@rainbow-me/rainbowkit';
import { AppProps } from 'next/app';
import { WagmiConfig } from 'wagmi';

export default function App({ Component, pageProps }: AppProps) {
  // You'll need to resolve AUTHENTICATION_STATUS here
  // using your application's authentication system.
  // It needs to be either 'loading' (during initial load),
  // 'unauthenticated' or 'authenticated'.

  return (
    <WagmiConfig {...etc}>
      <RainbowKitUseMoonProvider
       onSignIn={onSignIn} onSignOut={onSignOut}
      >
        <RainbowKitProvider {...etc}>
          <Component {...pageProps} />
        </RainbowKitProvider>
      </RainbowKitAuthenticationProvider>
    </WagmiConfig>
  );
}
```

## Example Project

<https://github.com/moon-up/moon-sdk/tree/main/examples/moon-sdk-rainbowkit-next-example>


# @moonup/moon-react

## Moon React

## **About Moon React:**

## **Installing Moon React:**

To utilize the Moon React package, first install it to the desired directory of the project:

#### To install Moon React

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/moon-react
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/moon-react
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm install @moonup/moon-react
```

{% endtab %}
{% endtabs %}

## Usage

```tsx
import { useMoonSDK } from '@moonup/moon-react';
```


# Context

## MoonSDKProvider Documentation

The `MoonSDKProvider` is a React context provider that provides access to the Moon SDK and other related functionality to its child components. This documentation page will guide you through the basics of using the `MoonSDKProvider` in your React project.

### Table of Contents

* Installation
* Usage
* Context Values
* Example

### Installation

To use the `MoonSDKProvider` in your project, you'll need to install the `@moonup/moon-react` package. You can install it using npm:

```bash
npm install @moonup/moon-react
```

### Usage

To use the `MoonSDKProvider`, you'll need to wrap your application with it. Here's an example of how to do this:

```javascript
import React from 'react';
import { MoonSDKProvider } from '@moonup/moon-react';
import App from './App';

export default function Main() {
  return (
    <MoonSDKProvider>
      <App />
    </MoonSDKProvider>
  );
}
```

### `MoonSDKProvider` context:

#### `connect(accessToken?: string, refreshToken?: string)`

Connects to the Moon API using the provided access and refresh tokens.

Example:

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function Connect() {
  const { connect } = useMoonSDK();

  const handleConnect = async () => {
    try {
      await connect('access-token', 'refresh-token');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Connect" onPress={handleConnect} />
  );
}
```

#### `disconnect()`

Disconnects from the Moon API.

Example:

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function Disconnect() {
  const { disconnect } = useMoonSDK();

  const handleDisconnect = async () => {
    try {
      await disconnect();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Disconnect" onPress={handleDisconnect} />
  );
}
```

#### `getUserSession()`

Retrieves the current user session.

Example:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function UserSession() {
  const { session, getUserSession } = useMoonSDK();

  const handleGetUserSession = async () => {
    try {
      await getUserSession();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Get User Session" onPress={handleGetUserSession} />
      <Text>{JSON.stringify(session)}</Text>
    </>
  );
}
```

#### `connectEthers()`

Connects to the Moon Ethers provider.

Example:

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function ConnectEthers() {
  const { connectEthers } = useMoonSDK();

  const handleConnectEthers = async () => {
    try {
      await connectEthers();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Connect Ethers" onPress={handleConnectEthers} />
  );
}
```

#### `disconnectEthers()`

Disconnects from the Moon Ethers provider.

Example:

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function DisconnectEthers() {
  const { disconnectEthers } = useMoonSDK();

  const handleDisconnectEthers = async () => {
    try {
      await disconnectEthers();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Disconnect Ethers" onPress={handleDisconnectEthers} />
  );
}
```

#### `request(args: any)`

Sends a request to the Moon Ethers provider.

Example:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function Request() {
  const { request } = useMoonSDK();
  const [result, setResult] = React.useState(null);

  const handleRequest = async () => {
    try {
      const response = await request({ method: 'eth_accounts' });
      setResult(response);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Request" onPress={handleRequest} />
      <Text>{JSON.stringify(result)}</Text>
    </>
  );
}
```

#### `signOut()`

Signs out the current user.

Example:

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function SignOut() {
  const { signOut } = useMoonSDK();

  const handleSignOut = async () => {
    try {
      await signOut();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Sign Out" onPress={handleSignOut} />
  );
}
```

#### `createWallet()`

Creates a new Ethereum wallet and adds it to the Moon SDK.

Example:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function CreateWallet() {
  const { wallets, createWallet } = useMoonSDK();

  const handleCreateWallet = async () => {
    try {
      await createWallet();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Create Wallet" onPress={handleCreateWallet} />
      {wallets.map((wallet) => (
        <Text key={wallet}>{wallet}</Text>
      ))}
    </>
  );
}
```

#### `listWallets()`

Retrieves the list of Ethereum wallets managed by the Moon SDK.

Example:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function WalletList() {
  const { wallets, listWallets } = useMoonSDK();

  const handleListWallets = async () => {
    try {
      await listWallets();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="List Wallets" onPress={handleListWallets} />
      {wallets.map((wallet) => (
        <Text key={wallet}>{wallet}</Text>
      ))}
    </>
  );
}
```

#### `setWallet(wallet: string)`

Sets the currently selected Ethereum wallet address.

Example:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function SetWallet() {
  const { wallet, setWallet } = useMoonSDK();

  const handleSetWallet = async () => {
    try {
      await setWallet('0x1234567890abcdef');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Set Wallet" onPress={handleSetWallet} />
      <Text>{wallet}</Text>
    </>
  );
}
```

#### `getChains()`

Retrieves the list of supported blockchain networks.

Example:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function ChainList() {
  const { chains, getChains } = useMoonSDK();

  const handleGetChains = async () => {
    try {
      await getChains();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Get Chains" onPress={handleGetChains} />
      {chains.map((chain) => (
        <Text key={chain.chain_id}>{chain.name}</Text>
      ))}
    </>
  );
}
```

### Example

Here's an example of how to use the `MoonSDKProvider` to retrieve the list of Ethereum wallets managed by the Moon SDK:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoonSDK } from '@moonup/moon-react';

export default function WalletList() {
  const { wallets, listWallets } = useMoonSDK();

  const handleListWallets = async () => {
    try {
      await listWallets();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="List Wallets" onPress={handleListWallets} />
      {wallets.map((wallet) => (
        <Text key={wallet}>{wallet}</Text>
      ))}
    </>
  );
}
```

In this example, we import the `useMoonSDK` hook from the `@moonup/moon-react` package and use it to access the `wallets` and `listWallets` context values. We then use these values to retrieve the list of Ethereum wallets managed by the Moon SDK and display them in a list


# hooks


# Components


# @moonup/moon-react-native

## @moonup/moon-react-native Package Documentation

## Getting Started with Moon React Native Package

This guide will help you get started with the `@moonup/moon-react-native` package, which provides a set of tools for interacting with various blockchain networks in a React Native application.

### Table of Contents

* Installation
* Initialization
* Setting up the Context Provider Globally
* Using Expo and TypeScript

### Installation

To install the `@moonup/moon-react-native` package, run the following command in your project directory:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/moon-react-native
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/moon-react-native
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/moon-react-native
```

{% endtab %}
{% endtabs %}

### Initialization

Before you can use the package, you need to initialize it in your application. This can be done by creating a new instance of the `MoonSDK` class and passing it to the `MoonContextProvider` component.

Here's an example of how to initialize the package in your `App.tsx` file:

```javascript
import React from 'react';
import { MoonSDK } from '@moonup/moon-sdk';
import { MoonContextProvider } from '@moonup/moon-react-native';

const moon = new MoonSDK({
  apiKey: 'your-api-key',
});

export default function App() {
  return (
    <MoonContextProvider moon={moon}>
      {/* Your app components go here */}
    </MoonContextProvider>
  );
}
```

Replace `'your-api-key'` with your actual API key.

### Setting up the Context Provider Globally

To make the `MoonSDK` instance and other context values available to all components in your application, you can set up the `MoonContextProvider` component at the root level of your application.

Here's an example of how to do this in your `App.tsx` file:

```javascript
import React from 'react';
import { MoonSDK } from '@moonup/moon-sdk';
import { MoonContextProvider } from '@moonup/moon-react-native';
import { NavigationContainer } from '@react-navigation/native';

import MainStackNavigator from './navigators/MainStackNavigator';

const moon = new MoonSDK({
  apiKey: 'your-api-key',
});

export default function App() {
  return (
    <MoonContextProvider moon={moon}>
      <NavigationContainer>
        <MainStackNavigator />
      </NavigationContainer>
    </MoonContextProvider>
  );
}
```

In this example, we've wrapped the `NavigationContainer` and `MainStackNavigator` components with the `MoonContextProvider` component, which makes the `MoonSDK` instance and other context values available to all components in the navigation hierarchy.

Sure, here's an example of how to use the Moon hooks in a subcomponent:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useSolanaSDK } from '@moonup/moon-react-native';

export default function BalanceDisplay() {
  const solanaSDK = useSolanaSDK();
  const [balance, setBalance] = React.useState(null);

  const handleGetBalance = async () => {
    try {
      const response = await solanaSDK.getBalance('your-solana-address');
      setBalance(response.data.balance);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Get Balance" onPress={handleGetBalance} />
      {balance && <Text>Balance: {balance}</Text>}
    </>
  );
}
```

In this example, we've created a new `BalanceDisplay` component that uses the `useSolanaSDK` hook to get the balance of a Solana address. The component renders a button that, when pressed, calls the `handleGetBalance` function to retrieve the balance and update the component's state. The component then displays the balance in a `Text` component.

You can use this component in your main component like this:

```javascript
import React from 'react';
import { View } from 'react-native';
import BalanceDisplay from './BalanceDisplay';

export default function App() {
  return (
    <View>
      <BalanceDisplay />
    </View>
  );
}
```

In this example, we've imported the `BalanceDisplay` component and used it in the `App` component's render method. The `BalanceDisplay` component is rendered inside a `View` component, which is a container component provided by React Native.


# Context

## MoonContextProvider Documentation

The `MoonContextProvider` is a React context provider that provides access to the Moon SDK and Ethers.js provider instances, as well as various authentication and session management functions. This documentation page will guide you through the basics of using the `MoonContextProvider` in your React Native project.

### Table of Contents

* Installation
* Usage
* Context Values
* Example

### Installation

To use the `MoonContextProvider` in your project, you'll need to install the `@moonup/moon-react-native` package. You can install it using npm:

```bash
npm install @moonup/moon-react-native
```

### Usage

To use the `MoonContextProvider`, you'll need to wrap your application with it. Here's an example of how to do this:

```javascript
import React from 'react';
import { MoonContextProvider } from '@moonup/moon-react-native';
import App from './App';

export default function Main() {
  return (
    <MoonContextProvider>
      <App />
    </MoonContextProvider>
  );
}
```

### API Reference

#### Context Provider Functions

**`connect(accessToken?: string, refreshToken?: string)`**

Connects to the Moon API using the provided access and refresh tokens.

Example:

```javascript
const handleConnect = async () => {
  try {
    await connect();
  } catch (error) {
    console.error(error);
  }
};
```

**`disconnect()`**

Disconnects from the Moon API.

Example:

```javascript
const handleDisconnect = async () => {
  try {
    await disconnect();
  } catch (error) {
    console.error(error);
  }
};
```

**`getUserSession()`**

Retrieves the current user session.

Example:

```javascript
const handleGetUserSession = async () => {
  try {
    const session = await getUserSession();
    console.log(session);
  } catch (error) {
    console.error(error);
  }
};
```

**`connectEthers()`**

Connects to the Ethers.js provider.

Example:

```javascript
const handleConnectEthers = async () => {
  try {
    await connectEthers();
  } catch (error) {
    console.error(error);
  }
};
```

**`disconnectEthers()`**

Disconnects from the Ethers.js provider.

Example:

```javascript
const handleDisconnectEthers = async () => {
  try {
    await disconnectEthers();
  } catch (error) {
    console.error(error);
  }
};
```

**`request(args: RequestArguments)`**

Sends a request to the Ethers.js provider.

Example:

```javascript
const handleRequest = async () => {
  try {
    const result = await request({ method: 'eth_accounts' });
    console.log(result);
  } catch (error) {
    console.error(error);
  }
};
```

**`signUp(email: string, password: string)`**

Signs up a new user with the provided email and password.

Example:

```javascript
const handleSignUp = async () => {
  try {
    await signUp('test@example.com', 'password');
  } catch (error) {
    console.error(error);
  }
};
```

**`signInWithPassword(email: string, password: string)`**

Signs in a user with the provided email and password.

Example:

```javascript
const handleSignInWithPassword = async () => {
  try {
    await signInWithPassword('test@example.com', 'password');
  } catch (error) {
    console.error(error);
  }
};
```

**`signOut()`**

Signs out the current user.

Example:

```javascript
const handleSignOut = async () => {
  try {
    await signOut();
  } catch (error) {
    console.error(error);
  }
};
```

**`signInWithDiscord()`**

Signs in a user using Discord OAuth.

Example:

```javascript
const handleSignInWithDiscord = async () => {
  try {
    await signInWithDiscord();
  } catch (error) {
    console.error(error);
  }
};
```

**`signInWithGithub()`**

Signs in a user using GitHub OAuth.

Example:

```javascript
const handleSignInWithGithub = async () => {
  try {
    await signInWithGithub();
  } catch (error) {
    console.error(error);
  }
};
```

**`signInWithTwitter()`**

Signs in a user using Twitter OAuth.

Example:

```javascript
const handleSignInWithTwitter = async () => {
  try {
    await signInWithTwitter();
  } catch (error) {
    console.error(error);
  }
};
```

**`signInWithGoogle()`**

Signs in a user using Google OAuth.

Example:

```javascript
const handleSignInWithGoogle = async () => {
  try {
    await signInWithGoogle();
  } catch (error) {
    console.error(error);
  }
};
```

**`sendMagicLink(email: string)`**

Sends a magic link to the provided email address.

Example:

```javascript
const handleSendMagicLink = async () => {
  try {
    await sendMagicLink('test@example.com');
  } catch (error) {
    console.error(error);
  }
};
```

#### Context Provider Variables

**`user`**

The current user object, or `null` if the user is not authenticated.

Example:

```javascript
console.log(user);
```

**`session`**

The current session object, or `null` if the user is not authenticated.

Example:

```javascript
console.log(session);
```

**`initialized`**

A boolean value indicating whether the authentication state has been initialized.

Example:

```javascript
console.log(initialized);
```

**`moon`**

An instance of the Moon SDK.

Example:

```javascript
console.log(moon);
```

**`ethers`**

An instance of the Ethers.js provider.

Example:

```javascript
console.log(ethers);
```

### Example

Here's an example of how to use the `MoonContextProvider` to sign in a user with Discord OAuth:

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useMoon } from '@moonup/moon-react-native';

export default function App() {
  const {
    user,
    session,
    initialized,
    moon,
    ethers,
    connect,
    disconnect,
    getUserSession,
    connectEthers,
    disconnectEthers,
    request,
    signUp,
    signInWithPassword,
    signOut,
    signInWithDiscord,
    signInWithGithub,
    signInWithTwitter,
    signInWithGoogle,
    sendMagicLink,
  } = useMoon();

  const handleSignUp = async () => {
    try {
      await signUp('test@example.com', 'password');
    } catch (error) {
      console.error(error);
    }
  };

  const handleSignInWithPassword = async () => {
    try {
      await signInWithPassword('test@example.com', 'password');
    } catch (error) {
      console.error(error);
    }
  };

  const handleSignOut = async () => {
    try {
      await signOut();
    } catch (error) {
      console.error(error);
    }
  };

  const handleConnect = async () => {
    try {
      await connect();
    } catch (error) {
      console.error(error);
    }
  };

  const handleDisconnect = async () => {
    try {
      await disconnect();
    } catch (error) {
      console.error(error);
    }
  };

  const handleGetUserSession = async () => {
    try {
      const session = await getUserSession();
      console.log(session);
    } catch (error) {
      console.error(error);
    }
  };

  const handleConnectEthers = async () => {
    try {
      await connectEthers();
    } catch (error) {
      console.error(error);
    }
  };

  const handleDisconnectEthers = async () => {
    try {
      await disconnectEthers();
    } catch (error) {
      console.error(error);
    }
  };

  const handleRequest = async () => {
    try {
      const result = await request({ method: 'eth_accounts' });
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  };

  const handleSendMagicLink = async () => {
    try {
      await sendMagicLink('test@example.com');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      {initialized && (
        <>
          {user ? (
            <>
              <Text>User: {user.email}</Text>
              <Button title="Sign out" onPress={handleSignOut} />
              <Button title="Connect" onPress={handleConnect} />
              <Button title="Disconnect" onPress={handleDisconnect} />
              <Button title="Get user session" onPress={handleGetUserSession} />
              <Button title="Connect Ethers" onPress={handleConnectEthers} />
              <Button title="Disconnect Ethers" onPress={handleDisconnectEthers} />
              <Button title="Request" onPress={handleRequest} />
            </>
          ) : (
            <>
              <Button title="Sign up" onPress={handleSignUp} />
              <Button title="Sign in with password" onPress={handleSignInWithPassword} />
              <Button title="Sign in with Discord" onPress={signInWithDiscord} />
              <Button title="Sign in with GitHub" onPress={signInWithGithub} />
              <Button title="Sign in with Twitter" onPress={signInWithTwitter} />
              <Button title="Sign in with Google" onPress={signInWithGoogle} />
              <Button title="Send magic link" onPress={handleSendMagicLink} />
            </>
          )}
        </>
      )}
    </>
  );
}
```

In this example, we import the `useMoon` hook from the `@moonup/moon-react-native` package and use it to access all of the context provider functions and variables. We then use these functions and variables to handle various authentication and session management tasks, such as signing up a new user, signing in a user with a password, signing out a user, connecting to the Moon API, disconnecting from the Moon API, getting the current user session, connecting to the Ethers.js provider, disconnecting from the Ethers.js provider, sending a request to the Ethers.js provider, and sending a magic link to a user's email address.

In this example, we import the `useMoon` hook from the `@moonup/moon-react-native` package and use it to access the `signInWithDiscord` function. We then use this function to sign in a user with Discord OAuth when the button is pressed.


# Hooks

## Moon SDK Hooks Documentation

The `@moonup/moon-react-native` package provides a set of hooks that allow you to easily interact with the Moon SDK in your React Native project. This documentation page will guide you through the basics of using these hooks.

### Table of Contents

* Installation
* Usage
* Hooks
* Examples

### Installation

To use the Moon SDK hooks in your project, you'll need to install the `@moonup/moon-react-native` package. You can install it using npm:

```bash
npm install @moonup/moon-react-native
```

### Usage

To use the Moon SDK hooks, you'll need to wrap your application with the `MoonContextProvider`. Here's an example of how to do this:

```javascript
import React from 'react';
import { MoonContextProvider } from '@moonup/moon-react-native';
import App from './App';

export default function Main() {
  return (
    <MoonContextProvider>
      <App />
    </MoonContextProvider>
  );
}
```

### Hooks

The `@moonup/moon-react-native` package provides the following hooks:

* `useMoonConnect`: A hook that returns the `connect` function from the Moon SDK context.
* `useMoonDisconnect`: A hook that returns the `disconnect` function from the Moon SDK context.
* `useUserSession`: A hook that returns the `getUserSession` function from the Moon SDK context.
* `useSolanaSDK`: A hook that returns the Solana SDK instance from the Moon SDK context.
* `useBitcoinSDK`: A hook that returns the Bitcoin SDK instance from the Moon SDK context.
* `useCosmosSDK`: A hook that returns the Cosmos SDK instance from the Moon SDK context.
* `useEosSDK`: A hook that returns the EOS SDK instance from the Moon SDK context.
* `useLitecoinSDK`: A hook that returns the Litecoin SDK instance from the Moon SDK context.
* `useRippleSDK`: A hook that returns the Ripple SDK instance from the Moon SDK context.
* `useTronSDK`: A hook that returns the Tron SDK instance from the Moon SDK context.
* `useBitcoincashSDK`: A hook that returns the Bitcoin Cash SDK instance from the Moon SDK context.
* `useDogecoinSDK`: A hook that returns the Dogecoin SDK instance from the Moon SDK context.
* `useAccountsSDK`: A hook that returns the Accounts SDK instance from the Moon SDK context.
* `useAaveSDK`: A hook that returns the Aave SDK instance from the Moon SDK context.
* `useConveyorfinanceSDK`: A hook that returns the Conveyor Finance SDK instance from the Moon SDK context.
* `useENSSDK`: A hook that returns the ENS SDK instance from the Moon SDK context.
* `useErc20SDK`: A hook that returns the ERC-20 SDK instance from the Moon SDK context.
* `useErc1155SDK`: A hook that returns the ERC-1155 SDK instance from the Moon SDK context.
* `useErc721SDK`: A hook that returns the ERC-721 SDK instance from the Moon SDK context.
* `useOneinchSDK`: A hook that returns the 1inch SDK instance from the Moon SDK context.
* `useUniswapSDK`: A hook that returns the Uniswap SDK instance from the Moon SDK context.
* `useYearnSDK`: A hook that returns the Yearn SDK instance from the Moon SDK context.

### Examples

Here are examples of how to use each of the Moon SDK hooks:

#### `useMoonConnect`

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonConnect } from '@moonup/moon-react-native';

export default function ConnectButton() {
  const connect = useMoonConnect();

  const handleConnect = async () => {
    try {
      await connect();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Connect" onPress={handleConnect} />
  );
}
```

#### `useMoonDisconnect`

```javascript
import React from 'react';
import { Button } from 'react-native';
import { useMoonDisconnect } from '@moonup/moon-react-native';

export default function DisconnectButton() {
  const disconnect = useMoonDisconnect();

  const handleDisconnect = async () => {
    try {
      await disconnect();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Button title="Disconnect" onPress={handleDisconnect} />
  );
}
```

#### `useUserSession`

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useUserSession } from '@moonup/moon-react-native';

export default function UserSession() {
  const getUserSession = useUserSession();
  const [session, setSession] = React.useState(null);

  const handleGetUserSession = async () => {
    try {
      const { data } = await getUserSession();
      setSession(data.session);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Get User Session" onPress={handleGetUserSession} />
      {session && <Text>User Session: {JSON.stringify(session)}</Text>}
    </>
  );
}
```

#### `useSolanaSDK`

```javascript
import React from 'react';
import { Button, Text } from 'react-native';
import { useSolanaSDK } from '@moonup/moon-react-native';

export default function SolanaBalance() {
  const solanaSDK = useSolanaSDK();
  const [balance, setBalance] = React.useState(null);

  const handleGetBalance = async () => {
    try {
      const response = await solanaSDK.getBalance('your-solana-address');
      setBalance(response.data.balance);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <>
      <Button title="Get Balance" onPress={handleGetBalance} />
      {balance && <Text>Balance: {balance}</Text>}
    </>
  );
}
```

The other hooks can be used in a similar way, by replacing `useSolanaSDK` with the appropriate hook name and calling the appropriate SDK method.


# @moonup/moon-api

## @moonup/moon-api Package Documentation

The `@moonup/moon-api` package is a comprehensive library that provides a set of APIs for interacting with various blockchain networks and decentralized finance (DeFi) protocols. This package includes support for Ethereum, Bitcoin, Bitcoin Cash, Dogecoin, Litecoin, EOS, Solana, Cosmos, Tron, and more.

## **Installing Moon API:**

To use the Moon API package, first install it to a project:

#### To install Moon **API**:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @moonup/moon-api
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @moonup/moon-api
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @moonup/moon-api
```

{% endtab %}
{% endtabs %}

### Usage

To use the `@moonup/moon-api` package, you'll first need to install it using a package manager like npm or Yarn. Once you've installed the package, you can import the classes and methods you need into your project.

Here's an example of how to use the `Accounts` class to create a new Ethereum account and transfer ETH:

```javascript
import { HttpClient, Accounts } from '@moonup/moon-api';

// Initialize the HttpClient with your API base URL and security worker
const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

// Create an instance of the Accounts class
const accounts = new Accounts(http);

// Create a new Ethereum account
const createAccountData = await accounts.createAccount({ private_key: 'your_private_key' });
console.log('New account created:', createAccountData.address);

// Transfer ETH from the new account to another account
const transferEthData = await accounts.transferEth(createAccountData.name, {
  to: '0xAnotherAccountAddress',
  value: '1000000000000000000', // 1 ETH in wei
});
console.log('Transfer successful:', transferEthData.transactionHash);
```

This example demonstrates how to use the `Accounts` class to create a new Ethereum account and transfer ETH to another account. The `HttpClient` class is used to make HTTP requests to the API, and the `securityWorker` function is used to add an authorization header to the requests.

### Initialization

To use the `@moonup/moon-api` package, you'll first need to initialize an `HttpClient` object with your API base URL and security worker. The security worker is a function that returns the headers to be included in the API requests. In this case, it returns an authorization header with a bearer token.

Here's an example of how to initialize the `HttpClient` object:

```javascript
import { HttpClient } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});
```

In this example, the `baseUrl` property is set to the URL of the API, and the `securityWorker` property is set to a function that returns an authorization header with a bearer token. The `securityData` object is passed to the `securityWorker` function, which can be used to retrieve the bearer token.

Once you've initialized the `HttpClient` object, you can use it to create instances of the classes provided by the `@moonup/moon-api` package. For example:

```javascript
import { Accounts } from '@moonup/moon-api';

const accounts = new Accounts(http);
```

In this example, the `Accounts` class is imported from the `@moonup/moon-api` package, and an instance of the class is created using the `HttpClient` object.

## Classes

The package is organized into several files, each containing a class that provides methods for interacting with a specific blockchain network or DeFi protocol. The main files in the package are:

\
[Aave](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/aave)

Provides methods for interacting with the Aave decentralized lending protocol, including borrowing, lending, and repaying assets.

[Accounts](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/accounts)

Provides methods for creating and managing Ethereum accounts, deploying contracts, signing messages and transactions, and transferring ETH.

[Bitcoin](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/bitcoin)

Provide methods for creating and managing Bitcoin accounts, and signing transactions

[Bitcoin Cash](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/bitcoin-cash)

Provide methods for creating and managing Bitcoin Cash accounts, and signing transactions

[ConveyorFinance](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/conveyorfinance)

Provide methods for interacting with the ConveyorFinance decentralized exchange (DEX) protocols, including swapping tokens and checking prices

[Cosmos](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/cosmos)

Provide methods for interacting with the Cosmos  blockchain networks, including creating and managing accounts, and signing transactions.

[Dogecoin](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/dogecoin)

Provide methods for creating and managing Dogecoin accounts, and signing transactions

[Ens](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/ens)

Provides methods for interacting with the Ethereum Name Service (ENS), including registering and resolving domain names.

[EOS](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/eos)

Provide methods for interacting with the EOS blockchain networks, including creating and managing accounts, and signing transactions.

[Erc20](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/erc20)

Provide methods for interacting with Ethereum-based tokens, including transferring tokens, checking balances, and approving contracts.

[Erc721](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/erc721)

Provide methods for interacting with Ethereum-based tokens, including transferring tokens, checking balances, and approving contracts.

[Erc1155](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/erc1155)

Provide methods for interacting with Ethereum-based tokens, including transferring tokens, checking balances, and approving contracts.

[Litecoin](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/litecoin)

Provide methods for creating and managing Litecoin accounts, and signing transactions

[OneInch](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/oneinch)

Provide methods for interacting with the 1inch decentralized exchange (DEX) protocols, including swapping tokens and checking prices

[OnRamper](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/onramper)

Provides methods for interacting with the Onramper fiat onramp service, allowing users to buy cryptocurrencies with fiat currency.

[Ripple](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/ripple)

Provides methods for interacting with the Ripple blockchain network, including creating and managing accounts, and sending and receiving payments.

[Solana](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/solana)

Provides methods for interacting with the Solana blockchain network, including creating and managing accounts, and sending and receiving tokens.

[Tron](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/tron)

Provides methods for interacting with the TRON blockchain network, including creating and managing accounts, and sending and receiving tokens.

[Uniswap](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/uniswap)

Provide methods for interacting with the Uniswap decentralized exchange (DEX) protocols, including swapping tokens and checking prices

[Yearn](/additional-moon-packages-7ca327c0bb2846d88b8ba5bc6caeaead/moonup-moon-api/yearn)

Provides methods for interacting with the Yearn decentralized finance (DeFi) protocol, including depositing, withdrawing, and earning yield on assets.

Overall, the `@moonup/moon-api` package is a powerful and flexible library that provides a wide range of APIs for interacting with various blockchain networks and DeFi protocols. Whether you're building a simple wallet application or a complex decentralized finance platform, this package has the tools you need to get the job done.


# Aave

Sure, here's the documentation for the `Aave` class from the `@moonup/moon-api` library, including an initialization section and usage examples for all of the functions:

### Initialization

To use the `Aave` class, you first need to initialize an `HttpClient` object with your API base URL and security worker. The security worker is a function that returns the headers to be included in the API requests. In this case, it returns an authorization header with a bearer token.

```javascript
import { HttpClient, Aave } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const aave = new Aave(http);
```

### Methods

#### `borrow(name: string, data: AaveInput, params: RequestParams = {})`

Borrows an asset from the Aave protocol.

* **Parameters:**
  * `name`: The name of the account.
  * `data`: An object containing the `asset` and `amount` properties.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `BorrowData` object.
* **Example:**

  ```javascript
  const borrowData = await aave.borrow('accountName', {
    asset: 'asset_address',
    amount: 'amount_to_borrow',
  });
  console.log('Borrow successful:', borrowData.transactionHash);
  ```

#### `lend(name: string, data: AaveInput, params: RequestParams = {})`

Lends an asset to the Aave protocol.

* **Parameters:**
  * `name`: The name of the account.
  * `data`: An object containing the `asset` and `amount` properties.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `LendData` object.
* **Example:**

  ```javascript
  const lendData = await aave.lend('accountName', {
    asset: 'asset_address',
    amount: 'amount_to_lend',
  });
  console.log('Lend successful:', lendData.transactionHash);
  ```

#### `repay(name: string, data: AaveInput, params: RequestParams = {})`

Repays a borrowed asset to the Aave protocol.

* **Parameters:**
  * `name`: The name of the account.
  * `data`: An object containing the `asset` and `amount` properties.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `RepayData` object.
* **Example:**

  ```javascript
  const repayData = await aave.repay('accountName', {
    asset: 'asset_address',
    amount: 'amount_to_repay',
  });
  console.log('Repay successful:', repayData.transactionHash);
  ```

#### `userReserveData(name: string, data: AaveInput, params: RequestParams = {})`

Retrieves data about a user's reserve in the Aave protocol.

* **Parameters:**
  * `name`: The name of the account.
  * `data`: An object containing the `asset` property.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `UserReserveDataData` object.
* **Example:**

  ```javascript
  const userReserveDataData = await aave.userReserveData('accountName', {
    asset: 'asset_address',
  });
  console.log('User reserve data:', userReserveDataData);
  ```

These examples assume that you have already initialized the `HttpClient` and `Aave` objects as shown in the initialization section. Make sure to replace the placeholders with actual values.


# Accounts

### Initialization

To use the `Accounts` class, you first need to initialize an `HttpClient` object with your API base URL and security worker. The security worker is a function that returns the headers to be included in the API requests. In this case, it returns an authorization header with a bearer token.

```javascript
import { HttpClient, Accounts } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const accounts = new Accounts(http);
```

### Methods

#### `broadcastTx(accountName: string, data: BroadcastInput, params: RequestParams = {})`

Broadcasts a raw transaction to the blockchain.

* **Parameters:**
  * `accountName`: The name of the account.
  * `data`: An object containing the `chainId` and `rawTransaction` properties.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `BroadcastTxData` object.
* **Example:**

  ```javascript
  const broadcastTxData = await accounts.broadcastTx('accountName', {
    chainId: '1',
    rawTransaction: '0xYourRawTransaction',
  });
  console.log('Transaction broadcasted:', broadcastTxData.transactionHash);
  ```

#### `createAccount(data: CreateAccountInput, params: RequestParams = {})`

Creates a new Ethereum account.

* **Parameters:**
  * `data`: An optional object containing the `private_key` property. If not provided, a new private key will be generated.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `CreateAccountData` object.
* **Example:**

  ```javascript
  const createAccountData = await accounts.createAccount({ private_key: 'your_private_key' });
  console.log('New account created:', createAccountData.address);
  ```

#### `deleteAccount(accountName: string, params: RequestParams = {})`

Deletes an existing Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account to delete.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `DeleteAccountData` object.
* **Example:**

  ```javascript
  const deleteAccountData = await accounts.deleteAccount('accountName');
  console.log('Account deleted:', deleteAccountData.success);
  ```

#### `deployContract(accountName: string, data: DeployInput, params: RequestParams = {})`

Deploys a new smart contract to the blockchain.

* **Parameters:**
  * `accountName`: The name of the account that will deploy the contract.
  * `data`: An object containing the `abi`, `bytecode`, `chain_id`, and `constructor_args` properties.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `DeployContractData` object.
* **Example:**

  ```javascript
  const deployContractData = await accounts.deployContract('accountName', {
    abi: 'contract_abi',
    bytecode: 'contract_bytecode',
    chain_id: '1',
    constructor_args: 'constructor_arguments',
  });
  console.log('Contract deployed:', deployContractData.contractAddress);
  ```

#### `encodeData(data: AbiEncodeInput, params: RequestParams = {})`

Encodes data using the ABI of a smart contract.

* **Parameters:**
  * `data`: An object containing the `abi`, `functionName`, and `params` properties.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to an `EncodeDataData` object.
* **Example:**

  ```javascript
  const encodeDataData = await accounts.encodeData({
    abi: 'contract_abi',
    functionName: 'functionName',
    params: ['param1', 'param2'],
  });
  console.log('Encoded data:', encodeDataData.data);
  ```

#### `estimateGas(accountName: string, data: InputBody, params: RequestParams = {})`

Estimates the amount of gas required to execute a transaction.

* **Parameters:**
  * `accountName`: The name of the account that will execute the transaction.
  * `data`: An object containing the transaction details.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to an `EstimateGasData` object.
* **Example:**

  ```javascript
  const estimateGasData = await accounts.estimateGas('accountName', {
    to: 'destination_address',
    value: 'transaction_value',
  });
  console.log('Estimated gas:', estimateGasData.gas);
  ```

#### `getAccount(accountName: string, params: RequestParams = {})`

Retrieves information about an Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `GetAccountData` object.
* **Example:**

  ```javascript
  const getAccountData = await accounts.getAccount('accountName');
  console.log('Account information:', getAccountData);
  ```

#### `getBalance({ accountName, ...query }: GetBalanceParams, params: RequestParams = {})`

Retrieves the balance of an Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account.
  * `query`: Optional query parameters, including `token_address` and `token_id`.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `GetBalanceData` object.
* **Example:**

  ```javascript
  const getBalanceData = await accounts.getBalance({ accountName: 'accountName' });
  console.log('Account balance:', getBalanceData.balance);
  ```

#### `getNonce(accountName: string, params: RequestParams = {})`

Retrieves the nonce of an Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `GetNonceData` object.
* **Example:**

  ```javascript
  const getNonceData = await accounts.getNonce('accountName');
  console.log('Account nonce:', getNonceData.nonce);
  ```

#### `listAccounts(params: RequestParams = {})`

Retrieves a list of all Ethereum accounts.

* **Parameters:**
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `ListAccountsData` object.
* **Example:**

  ```javascript
  const listAccountsData = await accounts.listAccounts();
  console.log('List of accounts:', listAccountsData.accounts);
  ```

#### `signMessage(accountName: string, data: SignMessage, params: RequestParams = {})`

Signs a message using an Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account.
  * `data`: An object containing the `message` property.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `SignMessageData` object.
* **Example:**

  ```javascript
  const signMessageData = await accounts.signMessage('accountName', { message: 'message_to_sign' });
  console.log('Signed message:', signMessageData.signature);
  ```

#### `signTransaction(accountName: string, data: InputBody, params: RequestParams = {})`

Signs a transaction using an Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account.
  * `data`: An object containing the transaction details.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `SignTransactionData` object.
* **Example:**

  ```javascript
  const signTransactionData = await accounts.signTransaction('accountName', {
    to: 'destination_address',
    value: 'transaction_value',
  });
  console.log('Signed transaction:', signTransactionData.rawTransaction);
  ```

#### `signTypedData(accountName: string, data: SignTypedData, params: RequestParams = {})`

Signs a typed data message using an Ethereum account.

* **Parameters:**
  * `accountName`: The name of the account.
  * `data`: An object containing the `data` property.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `SignTypedDataData` object.
* **Example:**

  ```javascript
  const signTypedDataData = await accounts.signTypedData('accountName', { data: 'typed_data_message' });
  console.log('Signed typed data:', signTypedDataData.signature);
  ```

#### `suggestGasPrice({ accountName, ...query }: SuggestGasPriceParams, params: RequestParams = {})`

Suggests a gas price for a transaction.

* **Parameters:**
  * `accountName`: The name of the account.
  * `query`: Optional query parameters, including `speed`.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `SuggestGasPriceData` object.
* **Example:**

  ```javascript
  const suggestGasPriceData = await accounts.suggestGasPrice({ accountName: 'accountName' });
  console.log('Suggested gas price:', suggestGasPriceData.gasPrice);
  ```

#### `transferEth(accountName: string, data: InputBody, params: RequestParams = {})`

Transfers ETH from one Ethereum account to another.

* **Parameters:**
  * `accountName`: The name of the source account.
  * `data`: An object containing the transaction details.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to a `TransferEthData` object.
* **Example:**

  ```javascript
  const transferEthData = await accounts.transferEth('accountName', {
    to: 'destination_address',
    value: 'transaction_value',
  });
  console.log('Transfer successful:', transferEthData.transactionHash);
  ```

These examples assume that you have already initialized the `HttpClient` and `Accounts` objects as shown in the provided code snippet. Make sure to replace the placeholders with actual values.


# Bitcoin

The `Bitcoin` class from the `@moonup/moon-api` package provides methods to interact with Bitcoin accounts and transactions.

### Initialization

To use the `Bitcoin` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Bitcoin` class:

```javascript
import { HttpClient, Bitcoin } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const bitcoin = new Bitcoin(http);
```

### Methods

The `Bitcoin` class provides the following methods:

1. `createBitcoinAccount(data: BitcoinInput, params?: RequestParams): Promise<CreateBitcoinAccountData>`

   * Creates a new Bitcoin account.
   * `data` is an object of type `BitcoinInput` that contains the necessary information to create the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `CreateBitcoinAccountData`.

   Example usage:

   ```javascript
   const data = {
     name: 'my_account',
     network: 'testnet',
   };
   const result = await bitcoin.createBitcoinAccount(data);
   console.log(result);
   ```
2. `getBitcoinAccount(accountName: string, params?: RequestParams): Promise<GetBitcoinAccountData>`

   * Retrieves information about a specific Bitcoin account.
   * `accountName` is a string that represents the name of the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetBitcoinAccountData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const result = await bitcoin.getBitcoinAccount(accountName);
   console.log(result);
   ```
3. `listBitcoinAccounts(params?: RequestParams): Promise<ListBitcoinAccountsData>`

   * Retrieves a list of all Bitcoin accounts.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ListBitcoinAccountsData`.

   Example usage:

   ```javascript
   const result = await bitcoin.listBitcoinAccounts();
   console.log(result);
   ```
4. `signBitcoinTransaction(accountName: string, data: BitcoinTransactionInput, params?: RequestParams): Promise<SignBitcoinTransactionData>`

   * Signs a Bitcoin transaction for a specific account.
   * `accountName` is a string that represents the name of the account.
   * `data` is an object of type `BitcoinTransactionInput` that contains the necessary information to sign the transaction.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SignBitcoinTransactionData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const data = {
     to: 'recipient_address',
     value: 0.1,
   };
   const result = await bitcoin.signBitcoinTransaction(accountName, data);
   console.log(result);
   ```

These methods can be used to perform various operations on Bitcoin accounts and transactions, such as creating new accounts, retrieving account information, signing transactions, and more. The `Bitcoin` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# Bitcoin Cash

The `Bitcoincash` class from the `@moonup/moon-api` package provides methods to interact with Bitcoin Cash accounts and transactions.

### Initialization

To use the `Bitcoincash` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Bitcoincash` class:

```javascript
import { HttpClient, Bitcoincash } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const bitcoincash = new Bitcoincash(http);
```

### Methods

The `Bitcoincash` class provides the following methods:

1. `createBitcoinCashAccount(data: BitcoinCashInput, params?: RequestParams): Promise<CreateBitcoinCashAccountData>`

   * Creates a new Bitcoin Cash account.
   * `data` is an object of type `BitcoinCashInput` that contains the necessary information to create the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `CreateBitcoinCashAccountData`.

   Example usage:

   ```javascript
   const data = {
     network: 'testnet',
     private_key: 'private_key',
   };
   const result = await bitcoincash.createBitcoinCashAccount(data);
   console.log(result);
   ```
2. `getBitcoinCashAccount(accountName: string, params?: RequestParams): Promise<GetBitcoinCashAccountData>`

   * Retrieves information about a specific Bitcoin Cash account.
   * `accountName` is a string that represents the name of the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetBitcoinCashAccountData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const result = await bitcoincash.getBitcoinCashAccount(accountName);
   console.log(result);
   ```
3. `listBitcoinCashAccounts(params?: RequestParams): Promise<ListBitcoinCashAccountsData>`

   * Retrieves a list of all Bitcoin Cash accounts.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ListBitcoinCashAccountsData`.

   Example usage:

   ```javascript
   const result = await bitcoincash.listBitcoinCashAccounts();
   console.log(result);
   ```
4. `signBitcoinCashTransaction(accountName: string, data: BitcoinCashTransactionInput, params?: RequestParams): Promise<SignBitcoinCashTransactionData>`

   * Signs a Bitcoin Cash transaction for a specific account.
   * `accountName` is a string that represents the name of the account.
   * `data` is an object of type `BitcoinCashTransactionInput` that contains the necessary information to sign the transaction.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SignBitcoinCashTransactionData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const data = {
     to: 'recipient_address',
     value: 0.1,
   };
   const result = await bitcoincash.signBitcoinCashTransaction(accountName, data);
   console.log(result);
   ```

These methods can be used to perform various operations on Bitcoin Cash accounts and transactions, such as creating new accounts, retrieving account information, signing transactions, and more. The `Bitcoincash` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# ConveyorFinance

### Usage

```typescript
import { HttpClient, RequestParams } from '@moonup/moon-api'';
import { Conveyorfinance } from '@moonup/moon-api';
import { TokenSwapParams } from '@moonup/moon-api';

// Initialize HttpClient
const httpClient = new HttpClient();

// Initialize Conveyorfinance
const conveyorfinance = new Conveyorfinance(httpClient);

// Example data
const name = 'myName';
const tokenSwapParams: TokenSwapParams = { /* your data here */ };

// Use swap
conveyorfinance.swap(name, tokenSwapParams);
```

### Conveyorfinance Class

This class provides methods to interact with the Conveyor Finance protocol.

#### `constructor(http: HttpClient<SecurityDataType>)`

Creates a new instance of the Conveyorfinance class.

#### `swap(name: string, data: TokenSwapParams, params: RequestParams = {})`

Initiates a token swap operation in the Conveyor Finance protocol.

Please note that this is a basic documentation. For a complete and useful documentation, each method should have a detailed description, including its parameters, return value, and any side effects or errors it might produce.


# Cosmos

The `Cosmos` class from the `@moonup/moon-api` package provides methods to interact with Cosmos accounts and transactions.

### Initialization

To use the `Cosmos` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Cosmos` class:

```javascript
import { HttpClient, Cosmos } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const cosmos = new Cosmos(http);
```

### Methods

The `Cosmos` class provides the following methods:

1. `createCosmosAccount(data: CosmosInput, params?: RequestParams): Promise<CreateCosmosAccountData>`

   * Creates a new Cosmos account.
   * `data` is an object of type `CosmosInput` that contains the necessary information to create the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `CreateCosmosAccountData`.

   Example usage:

   ```javascript
   const data = {
     name: 'my_account',
     network: 'testnet',
     private_key: 'private_key',
   };
   const result = await cosmos.createCosmosAccount(data);
   console.log(result);
   ```
2. `getCosmosAccount(accountName: string, params?: RequestParams): Promise<GetCosmosAccountData>`

   * Retrieves information about a specific Cosmos account.
   * `accountName` is a string that represents the name of the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetCosmosAccountData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const result = await cosmos.getCosmosAccount(accountName);
   console.log(result);
   ```
3. `listCosmosAccounts(params?: RequestParams): Promise<ListCosmosAccountsData>`

   * Retrieves a list of all Cosmos accounts.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ListCosmosAccountsData`.

   Example usage:

   ```javascript
   const result = await cosmos.listCosmosAccounts();
   console.log(result);
   ```
4. `signCosmosTransaction(accountName: string, data: CosmosTransactionInput, params?: RequestParams): Promise<SignCosmosTransactionData>`

   * Signs a Cosmos transaction for a specific account.
   * `accountName` is a string that represents the name of the account.
   * `data` is an object of type `CosmosTransactionInput` that contains the necessary information to sign the transaction.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SignCosmosTransactionData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const data = {
     to: 'recipient_address',
     value: 0.1,
   };
   const result = await cosmos.signCosmosTransaction(accountName, data);
   console.log(result);
   ```

These methods can be used to perform various operations on Cosmos accounts and transactions, such as creating new accounts, retrieving account information, signing transactions, and more. The `Cosmos` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# Dogecoin

The `Dogecoin` class from the `@moonup/moon-api` package provides methods to interact with Dogecoin accounts and transactions.

### Initialization

To use the `Dogecoin` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Dogecoin` class:

```javascript
import { HttpClient, Dogecoin } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const dogecoin = new Dogecoin(http);
```

### Methods

The `Dogecoin` class provides the following methods:

1. `createDogeCoinAccount(data: DogeCoinInput, params?: RequestParams): Promise<CreateDogeCoinAccountData>`

   * Creates a new Dogecoin account.
   * `data` is an object of type `DogeCoinInput` that contains the necessary information to create the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `CreateDogeCoinAccountData`.

   Example usage:

   ```javascript
   const data = {
     network: 'testnet',
     private_key: 'private_key',
   };
   const result = await dogecoin.createDogeCoinAccount(data);
   console.log(result);
   ```
2. `getDogeCoinAccount(accountName: string, params?: RequestParams): Promise<GetDogeCoinAccountData>`

   * Retrieves information about a specific Dogecoin account.
   * `accountName` is a string that represents the name of the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetDogeCoinAccountData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const result = await dogecoin.getDogeCoinAccount(accountName);
   console.log(result);
   ```
3. `listDogeCoinAccounts(params?: RequestParams): Promise<ListDogeCoinAccountsData>`

   * Retrieves a list of all Dogecoin accounts.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ListDogeCoinAccountsData`.

   Example usage:

   ```javascript
   const result = await dogecoin.listDogeCoinAccounts();
   console.log(result);
   ```
4. `signDogeCoinTransaction(accountName: string, data: DogeCoinTransactionInput, params?: RequestParams): Promise<SignDogeCoinTransactionData>`

   * Signs a Dogecoin transaction for a specific account.
   * `accountName` is a string that represents the name of the account.
   * `data` is an object of type `DogeCoinTransactionInput` that contains the necessary information to sign the transaction.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SignDogeCoinTransactionData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const data = {
     to: 'recipient_address',
     value: 0.1,
   };
   const result = await dogecoin.signDogeCoinTransaction(accountName, data);
   console.log(result);
   ```

These methods can be used to perform various operations on Dogecoin accounts and transactions, such as creating new accounts, retrieving account information, signing transactions, and more. The `Dogecoin` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# Ens

### Usage

```typescript
import { HttpClient, RequestParams } from '@moonup/moon-api';
import { Ens } from '@moonup/moon-api';
import { EnsResolveInput } from '@moonup/moon-api';

// Initialize HttpClient
const httpClient = new HttpClient();

// Initialize Ens
const ens = new Ens(httpClient);

// Example data
const ensResolveInput: EnsResolveInput = { /* your data here */ };

// Use resolve
ens.resolve(ensResolveInput);
```

### Ens Class

This class provides methods to interact with Ethereum Name Service (ENS).

#### `constructor(http: HttpClient<SecurityDataType>)`

Creates a new instance of the Ens class.

#### `resolve(data: EnsResolveInput, params: RequestParams = {})`

Resolves an ENS name to its corresponding address.

Please note that this is a basic documentation. For a complete and useful documentation, each method should have a detailed description, including its parameters, return value, and any side effects or errors it might produce.


# EOS

The `Eos` class from the `@moonup/moon-api` package provides methods to interact with EOS accounts and transactions.

### Initialization

To use the `Eos` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Eos` class:

```javascript
import { HttpClient, Eos } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const eos = new Eos(http);
```

### Methods

The `Eos` class provides the following methods:

1. `createEosAccount(data: EosInput, params?: RequestParams): Promise<CreateEosAccountData>`

   * Creates a new EOS account.
   * `data` is an object of type `EosInput` that contains the necessary information to create the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `CreateEosAccountData`.

   Example usage:

   ```javascript
   const data = {
     network: 'testnet',
     private_key: 'private_key',
   };
   const result = await eos.createEosAccount(data);
   console.log(result);
   ```
2. `getEosAccount(accountName: string, params?: RequestParams): Promise<GetEosAccountData>`

   * Retrieves information about a specific EOS account.
   * `accountName` is a string that represents the name of the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetEosAccountData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const result = await eos.getEosAccount(accountName);
   console.log(result);
   ```
3. `listEosAccounts(params?: RequestParams): Promise<ListEosAccountsData>`

   * Retrieves a list of all EOS accounts.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ListEosAccountsData`.

   Example usage:

   ```javascript
   const result = await eos.listEosAccounts();
   console.log(result);
   ```
4. `signEosTransaction(accountName: string, data: EosTransactionInput, params?: RequestParams): Promise<SignEosTransactionData>`

   * Signs an EOS transaction for a specific account.
   * `accountName` is a string that represents the name of the account.
   * `data` is an object of type `EosTransactionInput` that contains the necessary information to sign the transaction.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SignEosTransactionData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const data = {
     to: 'recipient_address',
     value: 0.1,
   };
   const result = await eos.signEosTransaction(accountName, data);
   console.log(result);
   ```

These methods can be used to perform various operations on EOS accounts and transactions, such as creating new accounts, retrieving account information, signing transactions, and more. The `Eos` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# Erc20

The `Erc20` class from the `@moonup/moon-api` package provides methods to interact with ERC-20 tokens.

### Initialization

To use the `Erc20` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Erc20` class:

```javascript
import { HttpClient, Erc20 } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const erc20 = new Erc20(http);
```

### Methods

The `Erc20` class provides the following methods:

1. `allowanceErc20(name: string, data: InputBody, params?: RequestParams): Promise<AllowanceErc20Data>`

   * Retrieves the amount of tokens that an owner has allowed to be spent by a spender.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `AllowanceErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     owner: 'owner_address',
     spender: 'spender_address',
     contract_address: 'contract_address',
   };
   const result = await erc20.allowanceErc20(name, data);
   console.log(result);
   ```
2. `approveErc20(name: string, data: InputBody, params?: RequestParams): Promise<ApproveErc20Data>`

   * Approves a spender to spend a certain amount of tokens on behalf of the owner.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ApproveErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     spender: 'spender_address',
     amount: '100',
     contract_address: 'contract_address',
   };
   const result = await erc20.approveErc20(name, data);
   console.log(result);
   ```
3. `balanceOfErc20(name: string, data: InputBody, params?: RequestParams): Promise<BalanceOfErc20Data>`

   * Retrieves the balance of a specific account for a given ERC-20 token.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `BalanceOfErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     account: 'account_address',
     contract_address: 'contract_address',
   };
   const result = await erc20.balanceOfErc20(name, data);
   console.log(result);
   ```
4. `decimalsErc20(name: string, data: InputBody, params?: RequestParams): Promise<DecimalsErc20Data>`

   * Retrieves the number of decimals used by a given ERC-20 token.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `DecimalsErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {  contract_address: 'contract_address'};
   const result = await erc20.decimalsErc20(name, data);
   console.log(result);
   ```
5. `nameErc20(name: string, data: InputBody, params?: RequestParams): Promise<NameErc20Data>`

   * Retrieves the name of a given ERC-20 token.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `NameErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {  contract_address: 'contract_address' };
   const result = await erc20.nameErc20(name, data);
   console.log(result);
   ```
6. `symbolErc20(name: string, data: InputBody, params?: RequestParams): Promise<SymbolErc20Data>`

   * Retrieves the symbol of a given ERC-20 token.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SymbolErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {  contract_address: 'contract_address' };
   const result = await erc20.symbolErc20(name, data);
   console.log(result);
   ```
7. `totalSupplyErc20(name: string, data: InputBody, params?: RequestParams): Promise<TotalSupplyErc20Data>`

   * Retrieves the total supply of a given ERC-20 token.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `TotalSupplyErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {  contract_address: 'contract_address',};
   const result = await erc20.totalSupplyErc20(name, data);
   console.log(result);
   ```
8. `transferErc20(name: string, data: InputBody, params?: RequestParams): Promise<TransferErc20Data>`

   * Transfers a certain amount of tokens from the sender's account to a recipient's account.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `TransferErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     to: 'recipient_address',
     amount: '100',
     contract_address: 'contract_address',
   };
   const result = await erc20.transferErc20(name, data);
   console.log(result);
   ```
9. `transferFromErc20(name: string, data: InputBody, params?: RequestParams): Promise<TransferFromErc20Data>`

   * Transfers a certain amount of tokens from a sender's account to a recipient's account on behalf of the sender.
   * `name` is a string that represents the name of the ERC-20 token.
   * `data` is an object of type `InputBody` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `TransferFromErc20Data`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     from: 'sender_address',
     to: 'recipient_address',
     amount: '100',
     contract_address: 'contract_address',

   };
   const result = await erc20.transferFromErc20(name, data);
   console.log(result);
   ```

These methods can be used to perform various operations on ERC-20 tokens, such as checking token balances, approving spenders, transferring tokens, and more. The `Erc20` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# Erc721

The `Erc721` class from the `@moonup/moon-api` package provides methods to interact with ERC-721 tokens.

### Initialization

To use the `Erc721` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Erc721` class:

```javascript
import { HttpClient, Erc721 } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const erc721 = new Erc721(http);
```

### Methods

The `Erc721` class provides the following methods:

1. `approve(name: string, data: Erc721Request, params?: RequestParams): Promise<ApproveData>`

   * Approves a spender to transfer a specific token on behalf of the owner.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ApproveData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     to: 'spender_address',
     token_id: 'token_id',
     contract_address: 'contract_address',
   };
   const result = await erc721.approve(name, data);
   console.log(result);
   ```
2. `balanceOf(name: string, data: Erc721Request, params?: RequestParams): Promise<BalanceOfResult>`

   * Retrieves the balance of a specific account for a given ERC-721 token.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `BalanceOfResult`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     owner: 'account_address',
     contract_address: 'contract_address',
   };
   const result = await erc721.balanceOf(name, data);
   console.log(result);
   ```
3. `getApproved(name: string, data: Erc721Request, params?: RequestParams): Promise<GetApprovedData>`

   * Retrieves the address of the spender that is approved to transfer a specific token.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetApprovedData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     token_id: 'token_id',
     contract_address: 'contract_address',
   };
   const result = await erc721.getApproved(name, data);
   console.log(result);
   ```
4. `isApprovedForAll(name: string, data: Erc721Request, params?: RequestParams): Promise<IsApprovedForAllResult>`

   * Checks if an operator is approved to transfer all tokens of a specific owner.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `IsApprovedForAllResult`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     owner: 'account_address',
     operator: 'operator_address',
     contract_address: 'contract_address',
   };
   const result = await erc721.isApprovedForAll(name, data);
   console.log(result);
   ```
5. `name(name: string, data: Erc721Request, params?: RequestParams): Promise<NameData>`

   * Retrieves the name of a given ERC-721 token.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `NameData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     contract_address: 'contract_address',
   };
   const result = await erc721.name(name, data);
   console.log(result);
   ```
6. `ownerOf(name: string, data: Erc721Request, params?: RequestParams): Promise<OwnerOfData>`

   * Retrieves the owner of a specific token.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `OwnerOfData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     token_id: 'token_id',
     contract_address: 'contract_address',
   };
   const result = await erc721.ownerOf(name, data);
   console.log(result);
   ```
7. `safeTransferFrom(name: string, data: Erc721Request, params?: RequestParams): Promise<SafeTransferFromResult>`

   * Transfers a specific token from one account to another.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SafeTransferFromResult`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     from: 'sender_address',
     to: 'recipient_address',
     token_id: 'token_id',
     contract_address: 'contract_address',
   };
   const result = await erc721.safeTransferFrom(name, data);
   console.log(result);
   ```
8. `setApprovalForAll(name: string, data: Erc721Request, params?: RequestParams): Promise<SetApprovalForAllResult>`

   * Approves or revokes an operator to transfer all tokens of a specific owner.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SetApprovalForAllResult`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     owner: 'account_address',
     operator: 'operator_address',
     approved: true,
     contract_address: 'contract_address',
   };
   const result = await erc721.setApprovalForAll(name, data);
   console.log(result);
   ```
9. `symbol(name: string, data: Erc721Request, params?: RequestParams): Promise<SymbolData>`

   * Retrieves the symbol of a given ERC-721 token.
   * `name` is a string that represents the name of the ERC-721 token.
   * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SymbolData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     contract_address: 'contract_address',
   };
   const result = await erc721.symbol(name, data);
   console.log(result);
   ```
10. `tokenUri(name: string, data: Erc721Request, params?: RequestParams): Promise<TokenUriData>`

    * Retrieves the URI of a specific token.
    * `name` is a string that represents the name of the ERC-721 token.
    * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
    * `params` is an optional object of type `RequestParams` that can be used to customize the request.
    * Returns a promise that resolves to an object of type `TokenUriData`.

    Example usage:

    ```javascript
    const name = 'my_token';
    const data = {
      token_id: 'token_id',
      contract_address: 'contract_address',
    };
    const result = await erc721.tokenUri(name, data);
    console.log(result);
    ```
11. `transfer(name: string, data: Erc721Request, params?: RequestParams): Promise<TransferData>`

    * Transfers a specific token from the sender's account to a recipient's account.
    * `name` is a string that represents the name of the ERC-721 token.
    * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
    * `params` is an optional object of type `RequestParams` that can be used to customize the request.
    * Returns a promise that resolves to an object of type `TransferData`.

    Example usage:

    ```javascript
    const name = 'my_token';
    const data = {
      from: 'sender_address',
      to: 'recipient_address',
      token_id: 'token_id',
      contract_address: 'contract_address',
    };
    const result = await erc721.transfer(name, data);
    console.log(result);
    ```
12. `transferFrom(name: string, data: Erc721Request, params?: RequestParams): Promise<TransferFromData>`

    * Transfers a specific token from a sender's account to a recipient's account on behalf of the sender.
    * `name` is a string that represents the name of the ERC-721 token.
    * `data` is an object of type `Erc721Request` that contains the necessary information to make the request.
    * `params` is an optional object of type `RequestParams` that can be used to customize the request.
    * Returns a promise that resolves to an object of type `TransferFromData`.

    Example usage:

    ```javascript
    const name = 'my_token';
    const data = {
      from: 'sender_address',
      to: 'recipient_address',
      token_id: 'token_id',
      contract_address: 'contract_address',
    };
    const result = await erc721.transferFrom(name, data);
    console.log(result);
    ```

These methods can be used to perform various operations on ERC-721 tokens, such as checking token balances, approving spenders, transferring tokens, and more. The `Erc721` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.

The `contract_address` and `token_id` properties are required for most of the `Erc721` class methods, as they are used to identify the specific ERC-721 token contract and token with which to interact. Without the `contract_address` and `token_id` properties, the method may not be able to correctly identify the token contract and token and may return incorrect results.


# Erc1155

The `Erc1155` class from the `@moonup/moon-api` package provides methods to interact with ERC-1155 tokens.

### Initialization

To use the `Erc1155` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Erc1155` class:

```javascript
import { HttpClient, Erc1155 } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const erc1155 = new Erc1155(http);
```

### Methods

The `Erc1155` class provides the following methods:

1. `balanceOf(name: string, data: Erc1155Request, params?: RequestParams): Promise<BalanceOfData>`

   * Retrieves the balance of a specific account for a given ERC-1155 token.
   * `name` is a string that represents the name of the ERC-1155 token.
   * `data` is an object of type `Erc1155Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `BalanceOfData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     account: 'account_address',
     id: 'token_id',
     contract_address: 'contract_address',
   };
   const result = await erc1155.balanceOf(name, data);
   console.log(result);
   ```
2. `balanceOfBatch(name: string, data: Erc1155Request, params?: RequestParams): Promise<BalanceOfBatchData>`

   * Retrieves the balance of multiple accounts for multiple ERC-1155 tokens.
   * `name` is a string that represents the name of the ERC-1155 token.
   * `data` is an object of type `Erc1155Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `BalanceOfBatchData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     accounts: ['account1_address', 'account2_address'],
     ids: ['token1_id', 'token2_id'],
     contract_address: 'contract_address',
   };
   const result = await erc1155.balanceOfBatch(name, data);
   console.log(result);
   ```
3. `isApprovedForAll(name: string, data: Erc1155Request, params?: RequestParams): Promise<IsApprovedForAllData>`

   * Checks if an operator is approved to transfer all tokens of a specific owner.
   * `name` is a string that represents the name of the ERC-1155 token.
   * `data` is an object of type `Erc1155Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `IsApprovedForAllData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     account: 'account_address',
     operator: 'operator_address',
     contract_address: 'contract_address',
   };
   const result = await erc1155.isApprovedForAll(name, data);
   console.log(result);
   ```
4. `safeBatchTransferFrom(name: string, data: Erc1155Request, params?: RequestParams): Promise<SafeBatchTransferFromData>`

   * Transfers multiple tokens from one account to another.
   * `name` is a string that represents the name of the ERC-1155 token.
   * `data` is an object of type `Erc1155Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SafeBatchTransferFromData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     from: 'sender_address',
     to: 'recipient_address',
     ids: ['token1_id', 'token2_id'],
     amounts: ['amount1', 'amount2'],
     contract_address: 'contract_address',
   };
   const result = await erc1155.safeBatchTransferFrom(name, data);
   console.log(result);
   ```
5. `safeTransferFrom(name: string, data: Erc1155Request, params?: RequestParams): Promise<SafeTransferFromData>`

   * Transfers a specific token from one account to another.
   * `name` is a string that represents the name of the ERC-1155 token.
   * `data` is an object of type `Erc1155Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SafeTransferFromData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     from: 'sender_address',
     to: 'recipient_address',
     id: 'token_id',
     amount: 'amount',
     contract_address: 'contract_address',
   };
   const result = await erc1155.safeTransferFrom(name, data);
   console.log(result);
   ```
6. `setApprovalForAll(name: string, data: Erc1155Request, params?: RequestParams): Promise<SetApprovalForAllData>`

   * Approves or revokes an operator to transfer all tokens of a specific owner.
   * `name` is a string that represents the name of the ERC-1155 token.
   * `data` is an object of type `Erc1155Request` that contains the necessary information to make the request.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SetApprovalForAllData`.

   Example usage:

   ```javascript
   const name = 'my_token';
   const data = {
     account: 'account_address',
     operator: 'operator_address',
     approved: true,
     contract_address: 'contract_address',
   };
   const result = await erc1155.setApprovalForAll(name, data);
   console.log(result);
   ```

These methods can be used to perform various operations on ERC-1155 tokens, such as checking token balances, approving operators, transferring tokens, and more. The `Erc1155` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.

The `contract_address` and `token_id` properties are required for most of the `Erc1155` class methods, as they are used to identify the specific ERC-1155 token contract and token with which to interact. Without the `contract_address` and `token_id` properties, the method may not be able to correctly identify the token contract and token and may return incorrect results.


# Litecoin

The `Litecoin` class from the `@moonup/moon-api` package provides methods to interact with Litecoin accounts and transactions.

### Initialization

To use the `Litecoin` class, you need to create an instance of it by passing an instance of the `HttpClient` class to its constructor. The `HttpClient` class is also part of the `@moonup/moon-api` package and provides a convenient way to make HTTP requests.

Here's an example of how to create an instance of the `Litecoin` class:

```javascript
import { HttpClient, Litecoin } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const litecoin = new Litecoin(http);
```

### Methods

The `Litecoin` class provides the following methods:

1. `createLitecoinAccount(data: LitecoinInput, params?: RequestParams): Promise<CreateLitecoinAccountData>`

   * Creates a new Litecoin account.
   * `data` is an object of type `LitecoinInput` that contains the necessary information to create the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `CreateLitecoinAccountData`.

   Example usage:

   ```javascript
   const data = {
     network: 'testnet',
     private_key: 'private_key',
   };
   const result = await litecoin.createLitecoinAccount(data);
   console.log(result);
   ```
2. `getLitecoinAccount(accountName: string, params?: RequestParams): Promise<GetLitecoinAccountData>`

   * Retrieves information about a specific Litecoin account.
   * `accountName` is a string that represents the name of the account.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `GetLitecoinAccountData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const result = await litecoin.getLitecoinAccount(accountName);
   console.log(result);
   ```
3. `listLitecoinAccounts(params?: RequestParams): Promise<ListLitecoinAccountsData>`

   * Retrieves a list of all Litecoin accounts.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `ListLitecoinAccountsData`.

   Example usage:

   ```javascript
   const result = await litecoin.listLitecoinAccounts();
   console.log(result);
   ```
4. `signLitecoinTransaction(accountName: string, data: LitecoinTransactionInput, params?: RequestParams): Promise<SignLitecoinTransactionData>`

   * Signs a Litecoin transaction for a specific account.
   * `accountName` is a string that represents the name of the account.
   * `data` is an object of type `LitecoinTransactionInput` that contains the necessary information to sign the transaction.
   * `params` is an optional object of type `RequestParams` that can be used to customize the request.
   * Returns a promise that resolves to an object of type `SignLitecoinTransactionData`.

   Example usage:

   ```javascript
   const accountName = 'my_account';
   const data = {
     to: 'recipient_address',
     value: 0.1,
   };
   const result = await litecoin.signLitecoinTransaction(accountName, data);
   console.log(result);
   ```

These methods can be used to perform various operations on Litecoin accounts and transactions, such as creating new accounts, retrieving account information, signing transactions, and more. The `Litecoin` class is a part of the `@moonup/moon-api` package, which provides a convenient way to interact with the Moon API.


# OneInch

The `OneInch` class from `@moonup/moon-api` provides a convenient way to interact with the 1inch API. This API allows you to perform various operations related to cryptocurrency swaps, approvals, and data retrieval.

Here's a detailed documentation for the `OneInch` class:

### Initialization

To use the `OneInch` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the 1inch API.

Here's an example of how to create an instance of the `OneInch` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { OneInch } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const oneinch = new OneInch(http);
```

### Class: OneInch

#### Methods

**`approveCallData(data: ApproveCallDataPayload, params?: RequestParams)`**

This method is used to get the call data for approving a token transfer.

* **Parameters:**
  * `data`: An object containing the token address and the amount to approve.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the call data for approving the token transfer.
* **Example:**

  ```javascript
  const data = {
    tokenAddress: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
    amount: '1000000000000000000', // 1 UNI
  };

  try {
    const response = await oneinch.approveCallData(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`approveSpender(data: ApproveSpenderPayload, params?: RequestParams)`**

This method is used to approve a spender to transfer tokens on your behalf.

* **Parameters:**
  * `data`: An object containing the token address and the spender address.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the transaction hash of the approval.
* **Example:**

  ```javascript
  const data = {
    tokenAddress: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
    spenderAddress: '0x88757f2f99175387ab4c6a4b3067c77a695b0349',
  };

  try {
    const response = await oneinch.approveSpender(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`protocols(data: ProtocolsPayload, params?: RequestParams)`**

This method is used to get the list of supported protocols.

* **Parameters:**
  * `data`: An object containing the chain ID.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the list of supported protocols.
* **Example:**

  ```javascript
  const data = {
    chainId: 1, // Ethereum Mainnet
  };

  try {
    const response = await oneinch.protocols(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`quote(data: QuotePayload, params?: RequestParams)`**

This method is used to get a quote for a swap.

* **Parameters:**
  * `data`: An object containing the source token address, the destination token address, and the amount to swap.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the quote for the swap.
* **Example:**

  ```javascript
  const data = {
    fromTokenAddress: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
    toTokenAddress: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
    amount: '1000000000000000000', // 1 UNI
  };

  try {
    const response = await oneinch.quote(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`swap(accountName: string, data: GetSwapDto, params?: RequestParams)`**

This method is used to perform a swap.

* **Parameters:**
  * `accountName`: The name of the account to use for the swap.
  * `data`: An object containing the swap details, such as the source token address, the destination token address, the amount to swap, and the slippage tolerance.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the transaction hash of the swap.
* **Example:**

  ```javascript
  const accountName = 'myAccount';
  const data = {
    fromTokenAddress: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
    toTokenAddress: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
    amount: '1000000000000000000', // 1 UNI
    slippage: 0.5, // 0.5% slippage tolerance
  };

  try {
    const response = await oneinch.swap(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`tokens(data: TokensPayload, params?: RequestParams)`**

This method is used to get the list of supported tokens.

* **Parameters:**
  * `data`: An object containing the chain ID.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the list of supported tokens.
* **Example:**

  ```javascript
  const data = {
    chainId: 1, // Ethereum Mainnet
  };

  try {
    const response = await oneinch.tokens(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `OneInch` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the 1inch API.

You can then use the `oneinch` instance to call the various methods of the `OneInch` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.


# OnRamper

The `OnRamper` class from `@moonup/moon-api` provides a convenient way to interact with the `OnRamper` API. This API allows you to perform various operations related to cryptocurrency purchases and sales, as well as retrieving supported assets, currencies, and payment types.

Here's a detailed documentation for the `OnRamper` class:

### Initialization

To use the `OnRamper` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Onramper API.

Here's an example of how to create an instance of the `OnRamper` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Onramper } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const onramper = new OnRamper(http);
```

### Class: OnRamper

#### Methods

**`onRamperCheckout(accountName: string, data: TransactionInput, params?: RequestParams)`**

This method is used to initiate a cryptocurrency purchase for a specific account.

* **Parameters:**
  * `accountName`: The name of the account to fund.
  * `data`: An object containing the transaction input details.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the checkout data.
* **Example:**

  ```javascript
  const accountName = 'myAccount';
  const data = {
    // Transaction input details
  };

  try {
    const response = await onramper.onRamperCheckout(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetQuotesBuy(query: OnRamperGetQuotesBuyParams, params?: RequestParams)`**

This method is used to get quotes for buying cryptocurrency.

* **Parameters:**
  * `query`: An object containing the parameters for the quote request.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the quotes for buying cryptocurrency.
* **Example:**

  ```javascript
  const query = {
    amount: 100,
    crypto: 'BTC',
    fiat: 'USD',
    // Other parameters
  };

  try {
    const response = await onramper.onRamperGetQuotesBuy(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetQuotesSell(query: OnRamperGetQuotesSellParams, params?: RequestParams)`**

This method is used to get quotes for selling cryptocurrency.

* **Parameters:**
  * `query`: An object containing the parameters for the quote request.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the quotes for selling cryptocurrency.
* **Example:**

  ```javascript
  const query = {
    amount: 1,
    crypto: 'BTC',
    fiat: 'USD',
    // Other parameters
  };

  try {
    const response = await onramper.onRamperGetQuotesSell(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedAssets(query: OnRamperGetSupportedAssetsParams, params?: RequestParams)`**

This method is used to get the supported assets for a specific country and source.

* **Parameters:**
  * `query`: An object containing the country and source.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported assets.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    source: 'buy',
  };

  try {
    const response = await onramper.onRamperGetSupportedAssets(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedCurrencies(query: OnRamperGetSupportedCurrenciesParams, params?: RequestParams)`**

This method is used to get the supported currencies for a specific type.

* **Parameters:**
  * `query`: An object containing the type.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported currencies.
* **Example:**

  ```javascript
  const query = {
    type: 'fiat',
  };

  try {
    const response = await onramper.onRamperGetSupportedCurrencies(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedDefaultsAll(query: OnRamperGetSupportedDefaultsAllParams, params?: RequestParams)`**

This method is used to get the supported defaults for a specific country and type.

* **Parameters:**
  * `query`: An object containing the country and type.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported defaults.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    type: 'buy',
  };

  try {
    const response = await onramper.onRamperGetSupportedDefaultsAll(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedOnRampsAll(params?: RequestParams)`**

This method is used to get all supported on-ramps.

* **Parameters:**
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to all supported on-ramps.
* **Example:**

  ```javascript
  try {
    const response = await onramper.onRamperGetSupportedOnRampsAll();
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedPaymentTypes(query: OnRamperGetSupportedPaymentTypesParams, params?: RequestParams)`**

This method is used to get the supported payment types for a specific country, fiat, and type.

* **Parameters:**
  * `query`: An object containing the country, fiat, and type.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported payment types.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    fiat: 'USD',
    type: 'buy',
  };

  try {
    const response = await onramper.onRamperGetSupportedPaymentTypes(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedPaymentTypesFiat(query: OnRamperGetSupportedPaymentTypesFiatParams, params?: RequestParams)`**

This method is used to get the supported payment types for a specific country and fiat.

* **Parameters:**
  * `query`: An object containing the country and fiat.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported payment types.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    fiat: 'USD',
  };

  try {
    const response = await onramper.onRamperGetSupportedPaymentTypesFiat(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Onramper` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Onramper API.

You can then use the `onramper` instance to call the various methods of the `Onramper` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.

Here's a detailed documentation for the `Onramper` class:

### Initialization

To use the `Onramper` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Onramper API.

Here's an example of how to create an instance of the `Onramper` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Onramper } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const onramper = new Onramper(http);
```

### Class: Onramper

#### Methods

**`onRamperCheckout(accountName: string, data: TransactionInput, params?: RequestParams)`**

This method is used to initiate a cryptocurrency purchase for a specific account.

* **Parameters:**
  * `accountName`: The name of the account to fund.
  * `data`: An object containing the transaction input details.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the checkout data.
* **Example:**

  ```javascript
  const accountName = 'myAccount';
  const data = {
    // Transaction input details
  };

  try {
    const response = await onramper.onRamperCheckout(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetQuotesBuy(query: OnRamperGetQuotesBuyParams, params?: RequestParams)`**

This method is used to get quotes for buying cryptocurrency.

* **Parameters:**
  * `query`: An object containing the parameters for the quote request.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the quotes for buying cryptocurrency.
* **Example:**

  ```javascript
  const query = {
    amount: 100,
    crypto: 'BTC',
    fiat: 'USD',
    // Other parameters
  };

  try {
    const response = await onramper.onRamperGetQuotesBuy(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetQuotesSell(query: OnRamperGetQuotesSellParams, params?: RequestParams)`**

This method is used to get quotes for selling cryptocurrency.

* **Parameters:**
  * `query`: An object containing the parameters for the quote request.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the quotes for selling cryptocurrency.
* **Example:**

  ```javascript
  const query = {
    amount: 1,
    crypto: 'BTC',
    fiat: 'USD',
    // Other parameters
  };

  try {
    const response = await onramper.onRamperGetQuotesSell(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedAssets(query: OnRamperGetSupportedAssetsParams, params?: RequestParams)`**

This method is used to get the supported assets for a specific country and source.

* **Parameters:**
  * `query`: An object containing the country and source.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported assets.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    source: 'buy',
  };

  try {
    const response = await onramper.onRamperGetSupportedAssets(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedCurrencies(query: OnRamperGetSupportedCurrenciesParams, params?: RequestParams)`**

This method is used to get the supported currencies for a specific type.

* **Parameters:**
  * `query`: An object containing the type.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported currencies.
* **Example:**

  ```javascript
  const query = {
    type: 'fiat',
  };

  try {
    const response = await onramper.onRamperGetSupportedCurrencies(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedDefaultsAll(query: OnRamperGetSupportedDefaultsAllParams, params?: RequestParams)`**

This method is used to get the supported defaults for a specific country and type.

* **Parameters:**
  * `query`: An object containing the country and type.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported defaults.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    type: 'buy',
  };

  try {
    const response = await onramper.onRamperGetSupportedDefaultsAll(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedOnRampsAll(params?: RequestParams)`**

This method is used to get all supported on-ramps.

* **Parameters:**
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to all supported on-ramps.
* **Example:**

  ```javascript
  try {
    const response = await onramper.onRamperGetSupportedOnRampsAll();
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedPaymentTypes(query: OnRamperGetSupportedPaymentTypesParams, params?: RequestParams)`**

This method is used to get the supported payment types for a specific country, fiat, and type.

* **Parameters:**
  * `query`: An object containing the country, fiat, and type.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported payment types.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    fiat: 'USD',
    type: 'buy',
  };

  try {
    const response = await onramper.onRamperGetSupportedPaymentTypes(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`onRamperGetSupportedPaymentTypesFiat(query: OnRamperGetSupportedPaymentTypesFiatParams, params?: RequestParams)`**

This method is used to get the supported payment types for a specific country and fiat.

* **Parameters:**
  * `query`: An object containing the country and fiat.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the supported payment types.
* **Example:**

  ```javascript
  const query = {
    country: 'US',
    fiat: 'USD',
  };

  try {
    const response = await onramper.onRamperGetSupportedPaymentTypesFiat(query);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Onramper` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Onramper API.

You can then use the `onramper` instance to call the various methods of the `Onramper` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks..


# Ripple

The `Ripple` class from `@moonup/moon-api` provides a convenient way to interact with the Ripple API. This API allows you to perform various operations related to Ripple accounts and transactions.

Here's a detailed documentation for the `Ripple` class:

### Initialization

To use the `Ripple` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Ripple API.

Here's an example of how to create an instance of the `Ripple` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Ripple } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const ripple = new Ripple(http);
```

### Class: Ripple

#### Methods

**`createRippleAccount(data: RippleInput, params?: RequestParams)`**

This method is used to create a new Ripple account.

* **Parameters:**
  * `data`: An object containing the input data for creating the Ripple account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the created Ripple account.
* **Example:**

  ```javascript
  const data = {
    network: 'testnet',
    // Other input data
  };

  try {
    const response = await ripple.createRippleAccount(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`getRippleAccount(accountName: string, params?: RequestParams)`**

This method is used to get the details of a specific Ripple account.

* **Parameters:**
  * `accountName`: The name of the Ripple account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the specified Ripple account.
* **Example:**

  ```javascript
  const accountName = 'myRippleAccount';

  try {
    const response = await ripple.getRippleAccount(accountName);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`listRippleAccounts(params?: RequestParams)`**

This method is used to list all Ripple accounts.

* **Parameters:**
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of all Ripple accounts.
* **Example:**

  ```javascript
  try {
    const response = await ripple.listRippleAccounts();
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`signRippleTransaction(accountName: string, data: RippleTransactionInput, params?: RequestParams)`**

This method is used to sign a Ripple transaction for a specific account.

* **Parameters:**
  * `accountName`: The name of the Ripple account.
  * `data`: An object containing the input data for signing the Ripple transaction.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the signed Ripple transaction.
* **Example:**

  ```javascript
  const accountName = 'myRippleAccount';
  const data = {
    to: 'rBTCAddress',
    value: 10,
    // Other input data
  };

  try {
    const response = await ripple.signRippleTransaction(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Ripple` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Ripple API.

You can then use the `ripple` instance to call the various methods of the `Ripple` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.


# Solana

The `Solana` class from `@moonup/moon-api` provides a convenient way to interact with the Solana blockchain. This API allows you to perform various operations related to Solana accounts and transactions.

Here's a detailed documentation for the `Solana` class:

### Initialization

To use the `Solana` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Solana API.

Here's an example of how to create an instance of the `Solana` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Solana } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const solana = new Solana(http);
```

### Class: Solana

#### Methods

**`createSolanaAccount(data: SolanaInput, params?: RequestParams)`**

This method is used to create a new Solana account.

* **Parameters:**
  * `data`: An object containing the input data for creating the Solana account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the created Solana account.
* **Example:**

  ```javascript
  const data = {
    network: 'devnet',
    // Other input data
  };

  try {
    const response = await solana.createSolanaAccount(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`getSolanaAccount(accountName: string, params?: RequestParams)`**

This method is used to get the details of a specific Solana account.

* **Parameters:**
  * `accountName`: The name of the Solana account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the specified Solana account.
* **Example:**

  ```javascript
  const accountName = 'mySolanaAccount';

  try {
    const response = await solana.getSolanaAccount(accountName);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`listSolanaAccounts(params?: RequestParams)`**

This method is used to list all Solana accounts.

* **Parameters:**
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of all Solana accounts.
* **Example:**

  ```javascript
  try {
    const response = await solana.listSolanaAccounts();
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`multiSignSolanaTransaction(accountName: string, data: SolanaSignTransactionInput, params?: RequestParams)`**

This method is used to multi-sign a Solana transaction for a specific account.

* **Parameters:**
  * `accountName`: The name of the Solana account.
  * `data`: An object containing the input data for multi-signing the Solana transaction.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the multi-signed Solana transaction.
* **Example:**

  ```javascript
  const accountName = 'mySolanaAccount';
  const data = {
    unsigned_tx: 'base64EncodedTransaction',
    network: 'devnet',
  };

  try {
    const response = await solana.multiSignSolanaTransaction(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`signSolanaTransaction(accountName: string, data: SolanaSignTransactionInput, params?: RequestParams)`**

This method is used to sign a Solana transaction for a specific account.

* **Parameters:**
  * `accountName`: The name of the Solana account.
  * `data`: An object containing the input data for signing the Solana transaction.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the signed Solana transaction.
* **Example:**

  ```javascript
  const accountName = 'mySolanaAccount';
  const data = {
    unsigned_tx: 'base64EncodedTransaction',
    network: 'devnet',
  };

  try {
    const response = await solana.signSolanaTransaction(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`transferSolanaTransaction(accountName: string, data: SolanaTransactionInput, params?: RequestParams)`**

This method is used to transfer SOL from a specific Solana account.

* **Parameters:**
  * `accountName`: The name of the Solana account.
  * `data`: An object containing the input data for the transfer.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the transfer transaction.
* **Example:**

  ```javascript
  const accountName = 'mySolanaAccount';
  const data = {
    to: 'destinationSolanaAddress',
    value: 1,
    network: 'devnet',
  };

  try {
    const response = await solana.transferSolanaTransaction(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`transferTokensSignSolanaTransaction(accountName: string, data: SolanaTransactionInput, params?: RequestParams)`**

This method is used to transfer tokens from a specific Solana account.

* **Parameters:**
  * `accountName`: The name of the Solana account.
  * `data`: An object containing the input data for the token transfer.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the token transfer transaction.
* **Example:**

  ```javascript
  const accountName = 'mySolanaAccount';
  const data = {
    to: 'destinationSolanaAddress',
    value: 1,
    network: 'devnet',
  };

  try {
    const response = await solana.transferTokensSignSolanaTransaction(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Solana` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Solana API.

You can then use the `solana` instance to call the various methods of the `Solana` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.


# Tron

The `Tron` class from `@moonup/moon-api` provides a convenient way to interact with the Tron blockchain. This API allows you to perform various operations related to Tron accounts and transactions.

Here's a detailed documentation for the `Tron` class:

### Initialization

To use the `Tron` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Tron API.

Here's an example of how to create an instance of the `Tron` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Tron } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const tron = new Tron(http);
```

### Class: Tron

#### Methods

**`createTronAccount(data: TronInput, params?: RequestParams)`**

This method is used to create a new Tron account.

* **Parameters:**
  * `data`: An object containing the input data for creating the Tron account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the created Tron account.
* **Example:**

  ```javascript
  const data = {
    network: 'mainnet',
    // Other input data
  };

  try {
    const response = await tron.createTronAccount(data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`getTronAccount(accountName: string, params?: RequestParams)`**

This method is used to get the details of a specific Tron account.

* **Parameters:**
  * `accountName`: The name of the Tron account.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the specified Tron account.
* **Example:**

  ```javascript
  const accountName = 'myTronAccount';

  try {
    const response = await tron.getTronAccount(accountName);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`listTronAccounts(params?: RequestParams)`**

This method is used to list all Tron accounts.

* **Parameters:**
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of all Tron accounts.
* **Example:**

  ```javascript
  try {
    const response = await tron.listTronAccounts();
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`signTronTransaction(accountName: string, data: TronTransactionInput, params?: RequestParams)`**

This method is used to sign a Tron transaction for a specific account.

* **Parameters:**
  * `accountName`: The name of the Tron account.
  * `data`: An object containing the input data for signing the Tron transaction.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the signed Tron transaction.
* **Example:**

  ```javascript
  const accountName = 'myTronAccount';
  const data = {
    to: 'tronAddress',
    value: 10,
    network: 'mainnet',
  };

  try {
    const response = await tron.signTronTransaction(accountName, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Tron` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Tron API.

You can then use the `tron` instance to call the various methods of the `Tron` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.


# Uniswap

The `Uniswap` class from `@moonup/moon-api` provides a convenient way to interact with the Uniswap protocol. This API allows you to perform various operations related to adding liquidity, removing liquidity, and swapping tokens on Uniswap.

Here's a detailed documentation for the `Uniswap` class:

### Initialization

To use the `Uniswap` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Uniswap API.

Here's an example of how to create an instance of the `Uniswap` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Uniswap } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const uniswap = new Uniswap(http);
```

### Class: Uniswap

#### Methods

**`addLiquidity(name: string, data: UniswapInput, params?: RequestParams)`**

This method is used to add liquidity to a Uniswap pool.

* **Parameters:**
  * `name`: The name of the Uniswap pool.
  * `data`: An object containing the input data for adding liquidity.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the liquidity addition.
* **Example:**

  ```javascript
  const name = 'myUniswapPool';
  const data = {
    token_a: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI
    token_b: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
    amount_a: '1000000000000000000', // 1 DAI
    amount_b: '1000000000000000000', // 1 WETH
    // Other input data
  };

  try {
    const response = await uniswap.addLiquidity(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`removeLiquidity(name: string, data: UniswapInput, params?: RequestParams)`**

This method is used to remove liquidity from a Uniswap pool.

* **Parameters:**
  * `name`: The name of the Uniswap pool.
  * `data`: An object containing the input data for removing liquidity.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the liquidity removal.
* **Example:**

  ```javascript
  const name = 'myUniswapPool';
  const data = {
    token_a: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI
    token_b: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
    liquidity: '1000000000000000000', // 1 LP token
    // Other input data
  };

  try {
    const response = await uniswap.removeLiquidity(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`swapExactEthForTokens(name: string, data: UniswapInput, params?: RequestParams)`**

This method is used to swap ETH for tokens on Uniswap.

* **Parameters:**
  * `name`: The name of the Uniswap pool.
  * `data`: An object containing the input data for the swap.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the swap.
* **Example:**

  ```javascript
  const name = 'myUniswapPool';
  const data = {
    token_a: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
    token_b: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI
    amount_a: '1000000000000000000', // 1 ETH
    // Other input data
  };

  try {
    const response = await uniswap.swapExactEthForTokens(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`swapExactTokensForTokens(name: string, data: UniswapInput, params?: RequestParams)`**

This method is used to swap tokens for tokens on Uniswap.

* **Parameters:**
  * `name`: The name of the Uniswap pool.
  * `data`: An object containing the input data for the swap.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the swap.
* **Example:**

  ```javascript
  const name = 'myUniswapPool';
  const data = {
    token_a: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI
    token_b: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
    amount_a: '1000000000000000000', // 1 DAI
    // Other input data
  };

  try {
    const response = await uniswap.swapExactTokensForTokens(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Uniswap` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Uniswap API.

You can then use the `uniswap` instance to call the various methods of the `Uniswap` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.


# Yearn

The `Yearn` class from `@moonup/moon-api` provides a convenient way to interact with the Yearn Finance protocol. This API allows you to perform various operations related to adding liquidity, removing liquidity, and managing your Yearn vaults.

Here's a detailed documentation for the `Yearn` class:

### Initialization

To use the `Yearn` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Yearn API.

Here's an example of how to create an instance of the `Yearn` class:

```javascript
import { HttpClient } from '@moonup/moon-api';
import { Yearn } from '@moonup/moon-api';

const http = new HttpClient({
  baseUrl: 'https://beta.usemoon.ai',
  securityWorker: async (securityData) => {
    return {
      headers: {
        Authorization: `Bearer ${securityData.token}`,
      },
    };
  },
});

const yearn = new Yearn(http);
```

### Class: Yearn

#### Methods

**`addLiquidity(name: string, data: InputBody, params?: RequestParams)`**

This method is used to add liquidity to a Yearn vault.

* **Parameters:**
  * `name`: The name of the Yearn vault.
  * `data`: An object containing the input data for adding liquidity.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the result of the liquidity addition.
* **Example:**

  ```javascript
  const name = 'myYearnVault';
  const data = {
    value: '1000000000000000000', // 1 ETH
    // Other input data
  };

  try {
    const response = await yearn.addLiquidity(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`addLiquidityWeth(name: string, data: InputBody, params?: RequestParams)`**

This method is used to add WETH liquidity to a Yearn vault.

* **Parameters:**
  * `name`: The name of the Yearn vault.
  * `data`: An object containing the input data for adding WETH liquidity.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the WETH liquidity addition.
* **Example:**

  ```javascript
  const name = 'myYearnVault';
  const data = {
    value: '1000000000000000000', // 1 WETH
    // Other input data
  };

  try {
    const response = await yearn.addLiquidityWeth(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`removeLiquidity(name: string, data: InputBody, params?: RequestParams)`**

This method is used to remove liquidity from a Yearn vault.

* **Parameters:**
  * `name`: The name of the Yearn vault.
  * `data`: An object containing the input data for removing liquidity.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the result of the liquidity removal.
* **Example:**

  ```javascript
  const name = 'myYearnVault';
  const data = {
    amount: '1000000000000000000', // 1 LP token
    // Other input data
  };

  try {
    const response = await yearn.removeLiquidity(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

**`removeLiquidityWeth(name: string, data: InputBody, params?: RequestParams)`**

This method is used to remove WETH liquidity from a Yearn vault.

* **Parameters:**
  * `name`: The name of the Yearn vault.
  * `data`: An object containing the input data for removing WETH liquidity.
  * `params`: Optional request parameters.
* **Returns:** A promise that resolves to the data of the WETH liquidity removal.
* **Example:**

  ```javascript
  const name = 'myYearnVault';
  const data = {
    amount: '1000000000000000000', // 1 WETH
    // Other input data
  };

  try {
    const response = await yearn.removeLiquidityWeth(name, data);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
  ```

#### Usage

To use the `Yearn` class, you need to create an instance of it with a configured `HttpClient`. The `HttpClient` is responsible for making HTTP requests to the Yearn API.

You can then use the `yearn` instance to call the various methods of the `Yearn` class. Make sure to handle any potential errors that may occur during the API calls using `try-catch` blocks.


# SDKs


# Flutter


# AaveApi


# moonsdk.model.AaveInput


# moonsdk.model.AaveReservesAPIResponse


# moonsdk.model.AaveReservesData


# openapi.model.AbiInput


# openapi.model.AbiItem


# openapi.model.AbiOutput


# moonsdk.model.AccountAPIResponse


# openapi.model.AccountControllerResponse


# openapi.model.AccountControllerResponseData


# moonsdk.model.AccountData


# moonsdk.model.AccountResponse


# AccountsApi


# moonsdk.model.AvailablePaymentMethod


# moonsdk.model.BalanceAPIResponse


# moonsdk.model.BalanceResponse


# moonsdk.model.BitcoinAPIResponse


# BitcoinApi


# moonsdk.model.BitcoinCashAPIResponse


# moonsdk.model.BitcoinCashInput


# moonsdk.model.BitcoinCashTransactionInput


# moonsdk.model.BitcoinCashTransactionOutput


# moonsdk.model.BitcoinInput


# moonsdk.model.BitcoinTransactionInput


# moonsdk.model.BitcoinTransactionOutput


# BitcoincashApi


# openapi.model.Block


# moonsdk.model.BroadCastRawTransactionAPIResponse


# moonsdk.model.BroadCastRawTransactionResponse


# moonsdk.model.BroadcastInput


# ConveyorFinanceApi


# moonsdk.model.ConveyorFinanceControllerResponse


# moonsdk.model.CosmosAPIResponse




---

[Next Page](/llms-full.txt/1)

