> For the complete documentation index, see [llms.txt](https://ours-meme.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.gitbook.io/ours.meme-docs/developer-sdk.md).

# Developer SDK

The `@ours-protocol/sdk-core` package is the official TypeScript and JavaScript SDK for building, deploying, and trading on the OURS platform (`ours.meme`). Powered by ethers v6, the SDK provides end-to-end programmatic access to token launches, bonding-curve price discovery, Uniswap v4 / PancakeSwap graduation routing, and non-custodial transaction workflows.

* Core Runtime Package: [`@ours-protocol/sdk-core`](https://www.npmjs.com/package/@ours-protocol/sdk-core)
* Documentation & Reference Package: [`@ours-protocol/sdk-docs`](https://www.npmjs.com/package/@ours-protocol/sdk-docs)
* Peer Dependency: `ethers@^6.15.0`
* Runtime Target: Node.js 22+ or modern browsers supporting native `fetch`, `Blob`, and `FormData`
* Supported Networks:
  * Robinhood Mainnet (Chain ID: `4663`, Native Currency: `ETH`)
  * BNB Smart Chain Testnet (Chain ID: `97`, Native Currency: `tBNB`)
  * BNB Smart Chain Mainnet (Chain ID: `56`, Native Currency: `BNB`)
* Settlement Assets: Native ETH / BNB (`ZeroAddress`), wrapped native tokens, and verified tokenized equities & ETFs ($NVDA, $TSLA,$SPY, etc.).

### 1. Architecture & Design Principles

* Ethers v6 Native Architecture: Built on top of ethers v6 abstractions (`Runner`, `Provider`, `Signer`), enabling seamless interoperability with browser wallets (MetaMask, Rabby) and Node.js backend services.
* Strict Non-Custodial Boundary: The SDK never asks for, manages, or stores private keys within client instances. Network switching and signing authority remain solely with the caller's wallet or signer.
* Modular Namespace Separation:
  * `client.auth`: Session authentication and in-memory cryptographic JWT handling.
  * `client.metadata`: Media file uploading (up to 5 MiB) and on-chain metadata building.
  * `client.launch`: Token address pre-allocation (`claimAddress`), fee policy selection, and deployment.
  * `client.tokens`: State inspection, lifecycle phase checking, and quote pair queries.
  * `client.trade`: Internal bonding-curve quoting, automated allowance management, and swaps.
  * `client.swap`: External graduated liquidity trading (Uniswap v4 / PancakeSwap Hook).
  * `client.transactions`: Decoupled transaction building, simulation, and manual multi-step execution.
* Backend Pre-Allocation & Salt Prediction: Eliminates high-cost client-side CREATE2 mining. Pre-computes valid deployment addresses via backend consensus while asserting on-chain factory validation.
* Two-Phase Separation:
  * Phase 0 (Curve): Handled by `client.trade` with programmatic slippage bounds and partial-fill refund calculation.
  * Phase 2 (Migrated): Handled by `client.swap` with net-of-fee Quoter evaluation.

### 2. Installation & Configuration

Install the runtime core SDK alongside ethers v6:

Bash

```
npm install @ours-protocol/sdk-core ethers@^6.15.0
```

To install the optional offline documentation package (contains HTML API docs, markdown references, and strategy policies):

Bash

```
npm install --save-dev @ours-protocol/sdk-docs
```

#### Client Initialization

The SDK uses the factory function `createClient()`. The connected runner dictates available features:

* Signer-backed: Supports quoting, simulations, automated approvals, and direct transaction broadcast.
* Provider-only: Supports public reads, quotes, and offline step construction (`build`), requiring an explicit `account` address.

**Browser Integration (MetaMask / Rabby / Web3 Wallets)**

TypeScript

```
import { BrowserProvider } from 'ethers';
import { createClient } from '@ours-protocol/sdk-core';

// Ensure the user's wallet is already switched to the target chain (e.g. 4663)
const provider = new BrowserProvider(window.ethereum);
await provider.send('eth_requestAccounts', []);
const signer = await provider.getSigner();

const client = createClient({
  chainId: 4663, // Robinhood Mainnet
  runner: signer,
  apiEnv: 'production', // 'production' | 'development'
});
```

**Node.js / Backend Trading Bot Integration**

TypeScript

```
import { JsonRpcProvider, Wallet } from 'ethers';
import { createClient } from '@ours-protocol/sdk-core';

const provider = new JsonRpcProvider(process.env.RPC_URL);
const signer = new Wallet(process.env.PRIVATE_KEY!, provider);

const client = createClient({
  chainId: 4663,
  runner: signer,
  approvalMode: 'max', // 'max' (default) or 'exact'
  slippageBps: 100,    // 1.00% default slippage
});
```

#### Client Configuration Parameters

<table data-header-hidden data-search="false"><thead><tr><th></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Option</strong></td><td><strong>Type</strong></td><td><strong>Default</strong></td><td><strong>Description</strong></td></tr><tr><td><code>chainId</code></td><td><code>number</code></td><td>Required</td><td>Target network (<code>4663</code>, <code>97</code>, or <code>56</code>).</td></tr><tr><td><code>runner</code></td><td><code>Provider | Signer</code></td><td>Required</td><td>Ethers v6 execution runner.</td></tr><tr><td><code>apiEnv</code></td><td><code>'production' | 'development'</code></td><td>Auto</td><td>Defaults to <code>'development'</code> on testnets (<code>97</code>) and <code>'production'</code> on mainnets (<code>4663</code>, <code>56</code>).</td></tr><tr><td><code>apiBaseUrl</code></td><td><code>string</code></td><td>Built-in</td><td>Optional base URL override for the OURS indexing API.</td></tr><tr><td><code>approvalMode</code></td><td><code>'max' | 'exact'</code></td><td><code>'max'</code></td><td>ERC-20 approval strategy. <code>'exact'</code> requests the exact amount needed for the trade.</td></tr><tr><td><code>slippageBps</code></td><td><code>number</code></td><td><code>100</code></td><td>Default slippage tolerance in basis points (100 bps = 1.00%).</td></tr><tr><td><code>deadlineSeconds</code></td><td><code>number</code></td><td><code>300</code></td><td>Transaction deadline offset in seconds (5 minutes).</td></tr><tr><td><code>migrationGasBuffer</code></td><td><code>bigint</code></td><td><code>3_000_000n</code></td><td>Headroom gas reserved for BSC automatic migration triggers.</td></tr></tbody></table>

### 3. Token Deployment Workflow (`client.launch`)

Deploying a meme project on OURS follows an orchestrated pipeline: Sign Session $$\rightarrow$$ Upload Asset $$\rightarrow$$ Construct Metadata $$\rightarrow$$ Claim Salt & Address $$\rightarrow$$ Deploy / Bundled First Buy.

```
import { ZeroAddress, parseUnits } from 'ethers';
import { readFile } from 'node:fs/promises';

// 1. Authenticate wallet session (signs an EIP-4361 message, retains JWT in-memory)
await client.auth.login();

// 2. Prepare logo: Upload local file or pass an existing HTTPS/IPFS URL
// Option A: Existing URL
const logoUrl = 'https://example.com/logo.png';

// Option B: Binary upload (Node.js)
const imageBytes = await readFile('logo.png');
const uploadedImage = await client.metadata.uploadLogo(
  new Blob([new Uint8Array(imageBytes)], { type: 'image/png' }),
  'logo.png'
);
const logoUrl = uploadedImage.url;

// 3. Assemble verified on-chain metadata
const metadata = client.metadata.build({
  name: 'Nvidia Pepe',
  symbol: 'PEPNVDA',
  logo: logoUrl,
  description: 'First tokenized equity meme on Robinhood Chain',
  socials: {
    website: 'https://pepnvda.com',
    twitter: 'https://x.com/pepnvda',
    telegram: 'https://t.me/pepnvda',
  },
});

// 4. Pre-claim verified token address and deployment salt
const claim = await client.launch.claimAddress();
console.log('Pre-allocated Token Address:', claim.address);

// 5. Build deployment payload
// For Robinhood Chain:
const launchInput = {
  chain: 'robinhood' as const,
  metadata,
  templateId: 0n,              // Selected template ID from client.launch.getTemplates()
  pairToken: ZeroAddress,       // ZeroAddress for ETH; or verified equity contract address
  claim,
  platformBps: 10000,           // 100% platform standard flywheel alignment
  initialBuyAmount: parseUnits('0.1', 18), // Optional atomic bundled first buy (in quote units)
};

// 6. Preview steps (optional inspection)
const plan = await client.launch.preview(launchInput);
console.log('Execution Steps:', plan.steps);

// 7. Execute deployment transaction
const result = await client.launch.send(launchInput, {
  onTransaction: (step, tx) => console.log(`Step ${step.kind} broadcast:`, tx.hash),
});

console.log('Token successfully launched at:', claim.address, 'State:', result.state);
```

### 4. Phase 0: Bonding Curve Trading (`client.trade`)

Tokens in the bonding curve phase are priced algorithmically. Swaps automatically handle token allowances, partial-fill adjustments, and unused budget refunds.

#### Interactive Quote & Swap Execution

TypeScript

```
import { parseUnits } from 'ethers';

const tokenAddress = claim.address;
const amountIn = parseUnits('0.5', 18); // 0.5 ETH or Quote Tokens

// 1. Calculate local deterministic quote
const quote = await client.trade.quote({
  token: tokenAddress,
  side: 'buy', // 'buy' (spends quote asset) | 'sell' (spends Meme)
  amountIn,
});

console.log({
  expectedOutput: quote.amountOut,
  minimumOutput:  quote.minAmountOut,
  feeDeducted:    quote.fee,
  refundBuffer:   quote.refund,
});

// 2. Execute buy: checks balance, requests minimal/max allowance, submits trade
const buyReceipt = await client.trade.buy({
  token: tokenAddress,
  amountIn,
});

// 3. Execute sell: sells 1,000 Meme tokens back into the curve
const sellReceipt = await client.trade.sell({
  token: tokenAddress,
  amountIn: parseUnits('1000', 18),
});
```

#### Execution Mechanics

* Input Units: All asset quantities must be supplied as native JavaScript `bigint` raw atomic units (wei). Query decimals via `client.tokens` before formatting.
* Automatic Refund Handling: In saturated curves, purchases that hit the graduation threshold spend only the required portion of the input; the remaining balance is refunded directly to the caller.
* Taxes & Royalties: Quoted returns dynamically account for base swap fees and any configured creator taxes.

### 5. Phase 2: Post-Graduation Trading (`client.swap`)

Once a bonding curve reaches 100% capacity, liquidity is locked into an external pool (Uniswap v4 on Robinhood Chain, PancakeSwap on BSC).

#### Inspecting Lifecycle State & Swapping

TypeScript

```
import { parseUnits } from 'ethers';

// 1. Verify token status
const state = await client.tokens.getState(tokenAddress);

if (state.phase === 'migrated') {
  const amountIn = parseUnits('1', 18);

  // 2. Fetch external Quoter output (net of pool & Hook fees)
  const quote = await client.swap.quote({
    token: tokenAddress,
    side: 'buy',
    amountIn,
  });

  console.log('Quoted External Output:', quote.amountOut);

  // 3. Broadcast external swap
  await client.swap.send({
    token: tokenAddress,
    side: 'buy',
    amountIn,
  });
} else if (state.phase === 'bonding_curve') {
  console.log('Token is still in bonding curve phase. Use client.trade instead.');
}
```

### 6. Offline Transaction Building & Self-Broadcasting

For systems that decouple quote/plan generation from transaction signing (e.g., hardware wallets, MPC vaults, or custom relayers), use `client.trade.build()`:

TypeScript

```
import { parseUnits } from 'ethers';

// Construct plan using a Provider-only or Signer client
const plan = await client.trade.build({
  token: tokenAddress,
  side: 'buy',
  amountIn: parseUnits('1', 18),
  account: '0xYourWalletAddress', // Required when runner has no attached signer
});

// Inspect decomposed steps
for (const step of plan.steps) {
  console.log(`Step: ${step.kind}`);
  console.log(`To:   ${step.to}`);
  console.log(`Data: ${step.data}`);
  console.log(`Val:  ${step.value}`);
  
  // Custom execution: broadcast via external signer and await receipt
}

// Or execute the entire pre-built plan using a signer-backed client
await client.transactions.send(plan);
```

### 7. Documentation & Reference Resources (`@ours-protocol/sdk-docs`)

Deep references, compiled ABIs, and policy manuals are available in the dedicated documentation package:

Bash

```
npm install --save-dev @ours-protocol/sdk-docs
```

* Interactive HTML Reference: Open `node_modules/@ours-protocol/sdk-docs/api/index.html` in any browser for class trees, parameter types, and full endpoint signatures.
* Contract ABIs: Available directly within the core runtime package under:

  Plaintext

  ```
  @ours-protocol/sdk-core/abi/<chain>/<ContractName>.json
  ```
* Network Constants: Mainnet and testnet factory bindings, hook addresses, and router endpoints are accessible via SDK root exports or the `@ours-protocol/sdk-docs` network overrides guide.
