> For the complete documentation index, see [llms.txt](https://kaze-ai.gitbook.io/kaze-ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kaze-ai.gitbook.io/kaze-ai/special-features/launch-spl-tokens-on-solana-with-pump.fun.md).

# Launch SPL Tokens on Solana with Pump.fun

This Python script provides functionality to launch custom SPL tokens on the Solana blockchain through Pump.fun, a platform that enables the creation and management of tokens.

**Key Components**

1. **Metadata Upload**
2. **Transaction Creation**
3. **Token Launch Process**

***

**Detailed Breakdown**

1. **Uploading Token Metadata**

   The `_upload_metadata` function handles the uploading of token metadata to the IPFS through **Pump.fun**. The metadata includes the token's name, ticker, description, and image URL. If additional options (such as social media links) are provided, they are included in the metadata upload.

   Copy

   ```
   async def _upload_metadata(
       session: aiohttp.ClientSession,
       token_name: str,
       token_ticker: str,
       description: str,
       image_url: str,
       options: Optional[PumpfunTokenOptions] = None
   ) -> Dict[str, Any]:
   ```

   * **Form Data**: This method forms the required data for metadata upload, which includes the token’s basic information, image, and any optional social media URLs.
   * **Image Download**: The image for the token is downloaded from the provided URL.
   * **IPFS Upload**: The metadata and image are uploaded to **Pump.fun**'s IPFS endpoint.
   * **Response**: On successful upload, it returns the metadata response, including the metadata URI.
2. **Creating the Token Transaction**

   The `_create_token_transaction` function prepares a transaction for minting the token on the Solana blockchain through **Pump.fun**. The transaction includes the token's metadata and minting information.

   Copy

   ```
   async def _create_token_transaction(
       session: aiohttp.ClientSession,
       agent: SolanaAgentKit,
       mint_keypair: Keypair,
       metadata_response: Dict[str, Any],
       options: Optional[PumpfunTokenOptions] = None
   ) -> bytes:
   ```

   * **Transaction Payload**: The payload for the transaction is built using the agent’s wallet address, mint keypair, and metadata URI.
   * **Transaction Request**: A request is made to the **Pump.fun** API to create the transaction.
   * **Serialized Transaction**: The transaction is returned as serialized data that can be signed and sent to the network.
3. **Launching the Token**

   The `launch_pumpfun_token` method orchestrates the process of launching a token. It includes uploading metadata, creating the transaction, and then signing and sending the transaction to the Solana network.

   Copy

   ```
   async def launch_pumpfun_token(
       agent: SolanaAgentKit,
       token_name: str,
       token_ticker: str,
       description: str,
       image_url: str,
       options: Optional[PumpfunTokenOptions] = None
   ) -> TokenLaunchResult:
   ```

   * **Mint Keypair**: A new mint keypair is generated for the token.
   * **Metadata Upload**: Calls `_upload_metadata` to upload the token's metadata to IPFS.
   * **Transaction Creation**: Calls `_create_token_transaction` to create the token transaction.
   * **Transaction Signing**: The transaction is signed using the mint keypair and sent to the Solana network via `sign_and_send_transaction`.

   **Result**: The method returns a `TokenLaunchResult` containing the transaction signature, mint address, and metadata URI.

***

**Helper Functions**

1. **`fix_asyncio_for_windows()`** This function is used to ensure compatibility of asynchronous tasks when running on Windows. It fixes an issue with the default event loop on Windows machines that might otherwise result in an `asyncio` exception.
2. **`sign_and_send_transaction()`** This function handles signing and sending the token transaction to the Solana blockchain. It is critical for the final step in the token launch process.

***

**Example Usage**

Below is an example of how to use the `PumpfunTokenManager` to launch a new token:

Copy

```
from solana.rpc.async_api import AsyncClient
from Kaze.agent import SolanaAgentKit

# Initialize the agent and other parameters
agent = SolanaAgentKit(client=AsyncClient("https://api.mainnet-beta.solana.com"))
token_name = "MyNewToken"
token_ticker = "MNTK"
description = "This is a test token."
image_url = "https://example.com/token_image.png"

# Optional: Provide additional configuration options
options = PumpfunTokenOptions(
    initial_liquidity_sol=1.0,  # Amount of SOL for initial liquidity
    slippage_bps=100,           # Slippage in basis points (1% = 100)
    priority_fee=50000          # Priority fee in lamports
)

# Launch the token
launch_result = await PumpfunTokenManager.launch_pumpfun_token(
    agent,
    token_name,
    token_ticker,
    description,
    image_url,
    options
)

# Print the launch result
print(f"Token launched successfully! Mint address: {launch_result.mint}")
print(f"Transaction signature: {launch_result.signature}")
```

***

**Error Handling**

The code handles various exceptions during the token launch process:

* **Metadata Upload**: If the metadata upload fails (e.g., image download or IPFS upload), it raises an error.
* **Transaction Creation**: If creating the transaction via the Pump.fun API fails, an exception is raised with the relevant error message.
* **Transaction Signing**: If the transaction fails during signing or submission to the Solana network, the exception is caught, and an appropriate error message is logged.

Example of error handling:

Copy

```
except Exception as error:
    logger.error(f"Error in launch_pumpfun_token: {error}")
    raise
```

***

**Key Features**

* **IPFS Metadata Upload**: Upload token metadata (name, symbol, description, image) to IPFS.
* **Transaction Creation**: Create and serialize the minting transaction for a new token.
* **Customizable Options**: Allow customization of initial liquidity, slippage, and priority fees for the token launch.
* **Solana Integration**: Full integration with Solana blockchain for minting and token management.
* **Error Logging**: Detailed logging and error handling throughout the process.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://kaze-ai.gitbook.io/kaze-ai/special-features/launch-spl-tokens-on-solana-with-pump.fun.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
