npm package: @mania-labs/mania-sdk
Description: Official SDK for interacting with the Mania Protocol - EVM Bonding Curve Token Launchpad
Author: Mania Protocol
Latest version: 1.0.3

# @mania-labs/mania-sdk

Official SDK for interacting with Mania Fun - an EVM-based token launchpad using bonding curves.

## Overview

Mania Protocol enables anyone to create and trade tokens on a bonding curve. When a token's bonding curve reaches the migration threshold (4 ETH), liquidity is automatically migrated to Uniswap V3, providing deep liquidity for the token.

### Key Features

- **Bonding Curve Trading**: Buy and sell tokens on a constant product AMM
- **Fair Launch**: Every token starts with the same bonding curve parameters
- **Automatic Migration**: Liquidity migrates to Uniswap V3 when threshold is reached
- **Creator Rewards**: Token creators earn 0.30% of all trading fees

### Important Notes

Tokens will be non-transferrable until migration. This is a critical security feature to prevent pre-initialisation of Uniswap pools at unfavourable prices. This ensures all tokens migrate with equal reserves, in a ratio of 4 ETH : 206.9M tokens.

The Mania Factory contract is upgradeable via a UUPS proxy pattern. Updates will be pushed sparingly, with significant notice for all integrators and SDK users. To stay informed about any upcoming updates, please join our Telegram channel at https://t.me/maniaFunDevelopers

## Installation

```bash
npm install @mania-labs/mania-sdk viem
# or
yarn add @mania-labs/mania-sdk viem
# or
pnpm add @mania-labs/mania-sdk viem
```

## Quick Start

```typescript
import { ManiaSDK } from "@mania-labs/mania-sdk";
import { parseEther } from "viem";
import { base } from "viem/chains";

// Initialize the SDK
const sdk = new ManiaSDK({
  factoryAddress: "0x...", // ManiaFactory contract address
  rpcUrl: "https://megaeth-testnet-v2.blockscout.com",
  chainId: 6543,
});

// Connect a wallet for transactions
sdk.connectWallet(process.env.PRIVATE_KEY!, base);

// Get token information
const tokenInfo = await sdk.getTokenInfo("0x...");
console.log("Current Price:", tokenInfo.currentPrice);
console.log("Migration Progress:", tokenInfo.migrationProgress, "%");
```

## Usage

### Creating a Token

```typescript
// Create a new token
const result = await sdk.create({
  name: "My Token",
  symbol: "MTK",
  uri: "ipfs://...", // Metadata URI (see Token Metadata below)
  creator: "0x...", // Creator address (receives fees)
});

console.log("Token created:", result.tokenAddress);
console.log("Transaction:", result.hash);
```

### Token Metadata

The `uri` parameter should point to an IPFS URL containing a JSON metadata file. You must upload your metadata JSON to IPFS first, then pass the resulting IPFS URL to the `uri` field.

**Metadata Structure:**

```json
{
  "name": "HOMER",
  "symbol": "HOMER",
  "description": "A description of your token",
  "image": "ipfs://bafybeigpul3iw2yok735e7ozc5siwg7l3gcmuovcsawkzelsq7kwbtexxu",
  "attributes": {
    "twitter": "https://x.com/yourproject",
    "website": "https://yourproject.com",
    "github": "https://github.com/yourproject",
    "discord": "https://discord.gg/yourproject"
  }
}
```

**Fields:**

| Field | Required | Description |
|-------|----------|-------------|
| `name` | Yes | Token display name |
| `symbol` | Yes | Token symbol (ticker) |
| `description` | No | Description of the token |
| `image` | No | IPFS URL to token image (e.g., `ipfs://bafy...`) |
| `attributes` | No | Social links and additional metadata |

**Adding an Image:**

1. Upload your image to IPFS (using Pinata, NFT.Storage, or any IPFS pinning service)
2. Get the resulting CID (e.g., `bafybeigpul3iw2yok735e7ozc5siwg7l3gcmuovcsawkzelsq7kwbtexxu`)
3. Use the `ipfs://` protocol prefix: `ipfs://<CID>`
4. Include this URL in the `image` field of your metadata JSON
5. Upload the complete metadata JSON to IPFS
6. Pass the metadata IPFS URL as the `uri` parameter when creating the token

**Example:**

```typescript
// After uploading metadata.json to IPFS and getting the CID
const metadataUri = "ipfs://bafkreihdwdcef3fksy7ygjxwfxjfujdi4mfg6rn4m5jqnz3gyvhqorvnrm";

const result = await sdk.create({
  name: "HOMER",
  symbol: "HOMER",
  uri: metadataUri,
  creator: "0x...",
});
```

### Create and Buy in One Transaction

```typescript
// Create token and buy in a single transaction
const result = await sdk.createAndBuy({
  name: "My Token",
  symbol: "MTK",
  uri: "ipfs://...",
  creator: "0x...",
  buyAmountEth: parseEther("0.1"), // Buy with 0.1 ETH
  minTokensOut: 0n, // Set minimum for slippage protection
});
```

### Buying Tokens

```typescript
import { parseEther } from "viem";

// Buy with manual slippage
const quote = await sdk.getBuyQuote(tokenAddress, parseEther("0.1"));
const minTokensOut = (quote * 99n) / 100n; // 1% slippage

await sdk.buy({
  token: tokenAddress,
  amountEth: parseEther("0.1"),
  minTokensOut,
});

// Or use built-in slippage calculation
await sdk.buyWithSlippage(
  tokenAddress,
  parseEther("0.1"),
  100 // 1% slippage in basis points
);
```

### Selling Tokens

```typescript
// Sell tokens
const tokenAmount = parseEther("1000"); // 1000 tokens
const quote = await sdk.getSellQuote(tokenAddress, tokenAmount);
const minEthOut = (quote * 99n) / 100n; // 1% slippage

await sdk.sell({
  token: tokenAddress,
  amountTokens: tokenAmount,
  minEthOut,
});

// Or use built-in slippage calculation
await sdk.sellWithSlippage(tokenAddress, tokenAmount, 100);
```

### Working with Bonding Curves

```typescript
import { BondingCurve } from "@mania-labs/mania-sdk";

// Get bonding curve instance for calculations
const curve = await sdk.getBondingCurveInstance(tokenAddress);

// Get current state
const state = curve.getState();
console.log("Virtual Token Reserves:", state.virtualTokenReserves);
console.log("Virtual ETH Reserves:", state.virtualEthReserves);

// Check status
console.log("Is Complete:", curve.isComplete());
console.log("Is Migrated:", curve.isMigrated());

// Get quotes locally (no RPC call)
const buyQuote = curve.getBuyQuote(parseEther("0.1"));
console.log("Tokens Out:", buyQuote.tokensOut);
console.log("Fee:", buyQuote.fee);
console.log("Price per Token:", buyQuote.pricePerToken);

// Calculate price impact
const priceImpact = curve.calculateBuyPriceImpact(parseEther("1"));
console.log("Price Impact:", priceImpact, "%");

// Get migration progress
console.log("Migration Progress:", curve.getMigrationProgress(), "%");
console.log("ETH Until Migration:", curve.getEthUntilMigration());
```

### Migration to Uniswap V3

```typescript
// Check if curve is complete
const isComplete = await sdk.isComplete(tokenAddress);

if (isComplete) {
  // Migrate liquidity to Uniswap V3
  // Note: Caller pays the migration fee (poolMigrationFee)
  const result = await sdk.migrate({ token: tokenAddress });
  console.log("Pool Address:", result.poolAddress);
}
```

### Watching Events

```typescript
// Watch for new token creations
const unwatch = sdk.watchCreateEvents((event) => {
  console.log("New token created:", event.mint);
  console.log("Name:", event.name);
  console.log("Symbol:", event.symbol);
  console.log("Creator:", event.creator);
});

// Watch trades on a specific token
sdk.watchTradeEvents(tokenAddress, (event) => {
  console.log(event.isBuy ? "Buy" : "Sell");
  console.log("ETH Amount:", event.ethAmount);
  console.log("Token Amount:", event.tokenAmount);
  console.log("User:", event.user);
});

// Watch for curve completions
sdk.watchCompleteEvents((event) => {
  console.log("Curve complete:", event.mint);
});

// Watch for migrations
sdk.watchMigrationEvents((event) => {
  console.log("Token migrated:", event.mint);
  console.log("Pool:", event.pool);
});

// Stop watching
unwatch();
```

### Reading Token Metadata

```typescript
// Get token name and symbol
const { name, symbol } = await sdk.getTokenMetadata(tokenAddress);
console.log("Name:", name);
console.log("Symbol:", symbol);
```

### Reading Global State

```typescript
const globalState = await sdk.getGlobalState();

console.log("Fee Basis Points:", globalState.feeBasisPoints); // 100 = 1%
console.log("Migration Enabled:", globalState.enableMigrate);
console.log("Pool Migration Fee:", globalState.poolMigrationFee);
console.log("Token Total Supply:", globalState.tokenTotalSupply);
```

### Trading Migrated Tokens

After a token migrates to Uniswap V3, use these methods to get quotes:

```typescript
import { parseEther } from "viem";

// Check if token has migrated
const isMigrated = await sdk.isMigrated(tokenAddress);

if (isMigrated) {
  // Get Uniswap V3 pool address
  const poolAddress = await sdk.getPoolAddress(tokenAddress);
  console.log("Pool:", poolAddress);

  // Get buy quote (ETH -> Token)
  const tokensOut = await sdk.getMigratedBuyQuote(tokenAddress, parseEther("1"));
  console.log("Tokens for 1 ETH:", tokensOut);

  // Get sell quote (Token -> ETH)
  const ethOut = await sdk.getMigratedSellQuote(tokenAddress, parseEther("1000"));
  console.log("ETH for 1000 tokens:", ethOut);
}
```

## Utility Functions

```typescript
import {
  formatEthValue,
  formatTokenAmount,
  parseEthValue,
  calculateWithSlippage,
  formatPrice,
  formatMarketCap,
  truncateAddress,
  bpsToPercent,
} from "@mania-labs/mania-sdk";

// Format values for display
console.log(formatEthValue(parseEther("1.234567"))); // "1.2346"
console.log(formatTokenAmount(parseEther("1234567890"))); // "1.23B"
console.log(formatPrice(1234567890123456n)); // "0.0012"
console.log(formatMarketCap(parseEther("1500"))); // "1.50K ETH"

// Calculate slippage
const minOut = calculateWithSlippage(parseEther("100"), 100); // 1% slippage

// Format addresses
console.log(truncateAddress("0x1234...5678")); // "0x1234...5678"

// Convert basis points
console.log(bpsToPercent(100)); // 1
```

## Constants

```typescript
import {
  MIGRATION_THRESHOLD,
  TOKENS_FOR_LP,
  PROTOCOL_FEE_BASIS_POINTS,
  CREATOR_FEE_BASIS_POINTS,
  DEFAULT_SLIPPAGE_BPS,
  UNISWAP_FEE_TIER,
} from "@mania-labs/mania-sdk";

// Migration threshold: 4 ETH
console.log(MIGRATION_THRESHOLD); // 4000000000000000000n

// Tokens allocated for LP: 206.9M
console.log(TOKENS_FOR_LP);

// Fee breakdown
console.log(PROTOCOL_FEE_BASIS_POINTS); // 70 (0.70%)
console.log(CREATOR_FEE_BASIS_POINTS); // 30 (0.30%)

// Default slippage: 1%
console.log(DEFAULT_SLIPPAGE_BPS); // 100

// Uniswap V3 fee tier: 0.3%
console.log(UNISWAP_FEE_TIER); // 3000
```

## Chain Configuration

```typescript
import { getChainConfig, CHAIN_CONFIGS } from "@mania-labs/mania-sdk";

// Get config for a specific chain
const baseConfig = getChainConfig(4326);
console.log(baseConfig?.factoryAddress);
console.log(baseConfig?.wethAddress);

// Or create SDK from chain ID
const sdk = ManiaSDK.fromChainId(4326, "https://megaeth.blockscout.com");
```

## Advanced Usage

### Custom Viem Clients

```typescript
import { createPublicClient, createWalletClient, http } from "viem";
import { base } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const publicClient = createPublicClient({
  chain: base,
  transport: http("https://megaeth.blockscout.com"),
});

const walletClient = createWalletClient({
  account: privateKeyToAccount("0x..."),
  chain: base,
  transport: http("https://megaeth.blockscout.com"),
});

const sdk = new ManiaSDK({
  factoryAddress: "0x...",
  chainId: 4326,
});

sdk.setPublicClient(publicClient);
sdk.setWalletClient(walletClient);
```

### Direct ABI Access

```typescript
import { MANIA_FACTORY_ABI, ERC20_ABI } from "@mania-labs/mania-sdk";
import { getContract } from "viem";

// Use ABIs directly with viem
const contract = getContract({
  address: factoryAddress,
  abi: MANIA_FACTORY_ABI,
  client: publicClient,
});
```

## Protocol Details

### Bonding Curve Formula

The protocol uses a constant product formula with virtual reserves:

```
tokensOut = (virtualTokenReserves * netEth) / (virtualEthReserves + netEth)
ethOut = (tokenAmount * virtualEthReserves) / (virtualTokenReserves + tokenAmount)
```

### Fee Structure

- **Total Trading Fee**: 1.00% (100 basis points)
  - Protocol Fee: 0.70%
  - Creator Fee: 0.30%

### Migration

When `realEthReserves` reaches 4 ETH:

1. Bonding curve is marked as complete
2. Anyone can call `migrate()` (paying `poolMigrationFee`)
3. Token trading is enabled (unlocked)
4. Liquidity (206.9M tokens + 4 ETH) is added to Uniswap V3
5. LP NFT is sent to dead address (locked forever)

## TypeScript Support

This package is written in TypeScript and includes full type definitions.

```typescript
import type {
  BondingCurveState,
  GlobalState,
  CreateTokenParams,
  BuyParams,
  SellParams,
  TokenInfo,
  TransactionResult,
} from "@mania-labs/mania-sdk";
```

## Error Handling

```typescript
try {
  await sdk.buy({
    token: tokenAddress,
    amountEth: parseEther("10"), // Too much ETH
    minTokensOut: 0n,
  });
} catch (error) {
  // Common errors:
  // - BuyExceedsMigrationThreshold: Buy would exceed 4 ETH threshold
  // - BondingCurveComplete: Trading has ended
  // - TooLittleTokensReceived: Slippage exceeded
  console.error("Transaction failed:", error);
}
```

## License

MIT