> For the complete documentation index, see [llms.txt](https://ours-meme-1.gitbook.io/ours.meme-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ours-meme-1.gitbook.io/ours.meme-docs/developer-sdk.md).

# Developer SDK

The `@ours-platform/launchpad-sdk` is the official TypeScript and JavaScript SDK for integrating OURS launchpad trading and market data into wallets, trading bots, aggregators, and analytics platforms.

* NPM Package: [`@ours-platform/launchpad-sdk`](https://www.npmjs.com/package/@ours-platform/launchpad-sdk)
* Latest Version: `0.1.1` (Public)
* License: `MIT`
* Network Target: Robinhood Chain (Chain ID: `4663`, Native Currency: `ETH`)
* Quote Currencies: Native ETH (`address(0)`), wrapped native assets, and 190+ compliant Robinhood Stock & ETF Tokens (e.g., NVDA, TSLA, AAPL, SPY)

### 1. Core Principles & Architecture

* Non-Custodial Design: The SDK does not hold private keys, sign transactions, or broadcast transactions automatically. Signing and submission remain strictly the responsibility of the integrator's wallet or signer.
* Deterministic Local Quotes: Bonding curve quotes read on-chain state and calculate the curve result locally without requiring an off-chain HTTP quote service, wallet balance, or token allowances.
* Dual Execution Venues:
  * Phase 0 (Bonding Curve): Local pricing, custom curve approvals, transaction simulation, and historical trade receipt parsing.
  * Phase 2 (Uniswap v4): Single-pool exact-input trading routed through the verified Ours Hook, official Quoter, Universal Router 2.1.2, and Permit2.
* Built-in Deployment Security: Pinned mainnet configuration (`MAINNET_DEPLOYMENT`) automatically verifies Factory addresses, runtime code hashes, and external contract bindings during chain reads.
* Numeric Precision: All on-chain asset quantities use native JavaScript `bigint` in the asset's smallest atomic unit (wei). Never cast raw on-chain amounts to JavaScript `number`.

### 2. Requirements & Installation

* Runtime: Node.js 20 or later.
* Format: Pure ESM module bundled with TypeScript declarations (`.d.ts`) and JSON ABIs. Browser environments require an ESM-compatible bundler.

Bash

```
npm install @ours-platform/launchpad-sdk
```

### 3. Initialization & Token Inspection

Connect to Robinhood Chain mainnet by initializing `APlatformClient` with your HTTP(S) RPC endpoint:

TypeScript

```
import { APlatformClient, jsonStringify } from '@ours-platform/launchpad-sdk';

const rpcUrl = 'https://rpc.robinhood-chain.org'; // Robinhood Chain RPC (Chain ID: 4663)
const sdk = new APlatformClient({ rpcUrl });

// Fetch token launch configuration and underlying quote asset
const launch = await sdk.getLaunch(tokenAddress);
const quoteAsset = await sdk.getAsset(launch.pairToken);

console.log(jsonStringify({ launch, quoteAsset }));
```

#### Token Lifecycle Phases (`launch.phase`)

The SDK evaluates the token lifecycle phase to determine valid trading routes:

| **Phase** | **Raw State**           | **Description & Supported SDK Methods**                                                    |
| --------- | ----------------------- | ------------------------------------------------------------------------------------------ |
| `0`       | `Bonding curve`         | Internal curve active. Use `quoteCurveTrade`, `simulateCurveTrade`, and curve methods.     |
| `1`       | `Migration pending`     | Bonding curve capacity met. Awaiting Uniswap v4 pool initialization and liquidity lock.    |
| `2`       | `External pool created` | Successfully graduated. Use `quoteExternalTrade`, `simulateExternalTrade`, and v4 methods. |
| `3`       | `Aborted`               | Inactive / aborted. No supported trading route available.                                  |

> Asset Addressing: A zero address (`0x0000000000000000000000000000000000000000`) denotes the native gas currency (`ETH`). Wrapped native assets and tokenized equities use their standard ERC-20 contract addresses. Always inspect asset decimals via `getAsset` before converting amounts with `parseUnits`.

### 4. Phase 0: Bonding Curve Trading

Bonding curve trading follows a deterministic pipeline: Local Quote $$ $\rightarrow$ $$ Prepare Approvals $$ $\rightarrow$ $$ Simulate Trade $$ $\rightarrow$ $$ Submit Transaction $$ $\rightarrow$ $$ Parse Receipt.

TypeScript

```
// 1. Calculate local curve quote (does not require wallet balance or allowance)
const quote = await sdk.quoteCurveTrade({
  token: tokenAddress,
  side: 'buy',        // 'buy': amountIn is quote asset; 'sell': amountIn is Meme token
  amountIn,           // bigint in asset's smallest unit
  recipient: walletAddress,
  slippageBps: 100,   // 1.00% slippage
});

const trade = { ...quote.tradeParameters, account: walletAddress };
console.log(jsonStringify(quote));

// 2. Validate wallet network and account
if (!signer.provider ||
    (await signer.provider.getNetwork()).chainId !== BigInt(sdk.deployment.chainId)) {
  throw new Error('Wrong wallet chain');
}
if ((await signer.getAddress()).toLowerCase() !== trade.account.toLowerCase()) {
  throw new Error('Wrong wallet account');
}

// 3. Prepare and submit finite ERC-20 approvals
for (const tx of await sdk.prepareCurveApprovals(trade)) {
  const receipt = await (await signer.sendTransaction(tx)).wait();
  if (!receipt || receipt.status !== 1) throw new Error('Approval failed');
}

// 4. Simulate the trade in the live account context
const plan = await sdk.simulateCurveTrade(trade);

// 5. Broadcast execution transaction via the signer
const receipt = await (await signer.sendTransaction(plan.transaction)).wait();
if (!receipt || receipt.status !== 1) throw new Error('Trade failed');

// 6. Decode individual trades and settled amounts from block receipt
const settlement = await sdk.parseCurveReceipt(tokenAddress, receipt);
console.log(jsonStringify(settlement.trades));
```

#### Curve Execution Semantics

* Buy Slippage Mode: Buy minimum output represents a minimum exchange rate across the full input budget (`buyMinimumMode: 'full-input-rate'`). A partial fill may deliver less than that absolute token quantity.
* Sell Output Floor: Sell minimum is enforced as an absolute token output floor.
* Safety Flags: The deployed Curve ABI contains no deadline, fee cap, or minimum-fill constraints; corresponding SDK protection flags default to `false`.
* Fee & Tax Separation: Receipt decoding isolates base swap fees and deployer taxes without double-charging.
* Refund Routing: Refunds return to the direct curve caller.

### 5. Phase 2: External Uniswap v4 Trading

Graduated tokens trade through the verified Ours Uniswap v4 Hook, official Quoter, Universal Router 2.1.2, and Permit2 using static-fee, single-pool, exact-input swaps:

TypeScript

```
// 1. Query external pool metadata and fetch net output quote
const pool = await sdk.getExternalPool(tokenAddress);
const quote = await sdk.quoteExternalTrade({
  token: tokenAddress,
  side: 'buy',
  amountIn,
  recipient: walletAddress,
  slippageBps: 100,
  deadline: Math.floor(Date.now() / 1000) + 300, // Unix timestamp (5-minute deadline)
});

const trade = { ...quote.tradeParameters, account: walletAddress };

// 2. Prepare two-layer approvals (ERC-20 -> Permit2 -> Universal Router)
for (const tx of await sdk.prepareExternalApprovals(trade)) {
  const receipt = await (await signer.sendTransaction(tx)).wait();
  if (!receipt || receipt.status !== 1) throw new Error('Approval failed');
}

// 3. Simulate and broadcast swap
const plan = await sdk.simulateExternalTrade(trade);
const receipt = await (await signer.sendTransaction(plan.transaction)).wait();
if (!receipt || receipt.status !== 1) throw new Error('Trade failed');
```

#### v4 Trading Constraints

* Two-Layer Approvals: Non-native ERC-20 inputs require approvals from the ERC-20 token to Permit2, followed by Permit2 allowance to Universal Router. Native currency (`ETH`) buys require zero approvals.
* Net Output Quoting: The official Quoter returns expected net output factoring in pool and Hook fees.
* Unsupported Routing: Dynamic-fee pools, exact-output swaps, multihop routing, meta-transactions/sponsored gas, and rebasing or transfer-tax tokens are not supported.

### 6. Real-Time Market Data (`MarketClient`)

Market data is served via a dedicated HTTP service. Initialize `MarketClient` to consume live token lists, OHLCV candles, trades, and holders:

TypeScript

```
import { MarketClient } from '@ours-platform/launchpad-sdk';

const market = new MarketClient({
  baseUrl: 'https://dev-oursmeme-api.openhub.network/api', // Deployment API base URL
  timeoutMs: 10000,
});

// List tokens: 'latest' | 'graduating' | 'graduated'
const tokens = await market.listTokens({ page: 1, pageSize: 20, type: 'graduated' });

// Search tokens by ticker or keyword
const matches = await market.searchTokens('NVDA', { page: 1, pageSize: 20 });

// Query token details
const detail = await market.getToken(tokenAddress);

// Query trades (market: 0 = Curve trades, market: 1 = Uniswap v4 trades; omit for both)
const trades = await market.getTrades(tokenAddress, { page: 1, pageSize: 20, market: 1 });

// Query OHLCV Kline candles
const candles = await market.getCandles(tokenAddress, {
  interval: '1m', // 1m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, 1d
  from: startTimestamp,
  to: endTimestamp,
  limit: 500, // Max 1,000
});

// Query top 50 token holders ranked by balance
const holders = await market.getHolders(tokenAddress);
```

#### API Endpoints & Return Types

| **Method**     | **HTTP Path**       | **Response Body Format** |
| -------------- | ------------------- | ------------------------ |
| `listTokens`   | `GET token/list`    | `{ list, total }`        |
| `searchTokens` | `GET token/search`  | `{ list, total }`        |
| `getToken`     | `GET token/detail`  | `Token details`          |
| `getTrades`    | `GET token/trades`  | `{ list, total }`        |
| `getCandles`   | `GET token/kline`   | `{ list }`               |
| `getHolders`   | `GET token/holders` | `{ list }`               |

#### Field Units & Numerical Standards

* Valuations: `price` and candle `open`, `high`, `low`, and `close` are denominated in USD per token. `market_cap` is in USD.
* 24h Volume: `volume_24h` estimates the rolling 1,440 complete minutes of quote-asset turnover in USD.
* Volume Quantities: Candle `token_volume` and `quote_volume` are full asset quantities (not raw wei and not USD).
* String Preservation: Trade `token_amount`, `quote_amount`, `fee_amount`, `tax_amount`, `block_number`, and `trade_time` are formatted as raw strings. Do not parse large integers directly into JavaScript numbers.

### 7. Error Handling & Deployment Verification

The SDK checks network configurations and pinned runtime bytecode hashes during on-chain reads. Errors throw standard `SdkError.code` identifiers:

| **SdkError.code**        | **Cause**                                                      | **Resolution**                                                |
| ------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------- |
| `WRONG_CHAIN`            | RPC or connected signer chain ID does not match `4663`.        | Switch wallet network to Robinhood Chain mainnet.             |
| `VENUE_CLOSED`           | Attempted curve trading on a graduated token (or v4 on curve). | Verify `launch.phase` before constructing quotes.             |
| `DEPLOYMENT_MISMATCH`    | Pinned contract bytecode hash mismatch detected.               | Verify RPC provider integrity; do not trust unverified nodes. |
| `SLIPPAGE_EXCEEDED`      | Price moved beyond user-defined `slippageBps`.                 | Adjust slippage tolerance or reduce transaction size.         |
| `INSUFFICIENT_LIQUIDITY` | Trade size exceeds bonding curve capacity or pool depth.       | Check current curve reserve or external pool depth.           |
| `TRANSACTION_FAILED`     | Simulation or on-chain transaction execution reverted.         | Inspect transaction parameters, allowances, and balances.     |

### 8. Version Scope Boundaries (v0.1.1)

To maintain strict contract security and integration boundaries in release `v0.1.1`:

* Supported Workflows: Bonding curve quotes, ERC-20 approvals, transaction simulation, execution, receipt decoding, Uniswap v4 Hook trading, and Market API indexing.
* Out-of-Scope Workflows: Token creation, graduation execution, platform fee flywheel distribution, dividend claims, and contribution point claims are managed directly through smart contracts and are not bundled transaction flows in this SDK release.
* Exported Artifacts: Raw JSON ABIs are available directly under `@ours-platform/launchpad-sdk/abi/*.json` for custom indexers and developer tooling.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://ours-meme-1.gitbook.io/ours.meme-docs/developer-sdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
