npm package: @megaflow-labs/sdk
Description: Batch transaction SDK for MegaETH — compose, simulate and execute multiple on-chain operations in a single atomic transaction.
Author: MegaFlow Labs
Latest version: 0.1.2

# @megaflow-labs/sdk

**Batch transaction SDK for MegaETH** — compose, simulate and execute multiple on-chain operations in a single atomic transaction.

[![npm](https://img.shields.io/npm/v/@megaflow-labs/sdk)](https://www.npmjs.com/package/@megaflow-labs/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)](https://www.typescriptlang.org/)

---

## Why MegaFlow?

On standard EVM chains, sending multiple transactions requires multiple wallet confirmations and multiple block waits. MegaFlow solves this:

| | Without MegaFlow | With MegaFlow |
|---|---|---|
| Approve + Swap | 2 wallet popups, 2 blocks | **1 wallet popup, 1 block** |
| Failure safety | First tx may succeed, second may fail | **All-or-nothing (atomic)** |
| Code complexity | ABI encoding, fee math, polling | **Chainable one-liners** |

---

## Installation

```bash
npm install @megaflow-labs/sdk
```

> **Node.js ≥ 18** required. `viem` is a peer dependency — but all commonly used viem utilities are **re-exported from the SDK** so you rarely need to install it separately.

---

## Quick Start

```typescript
import { MegaFlowClient, MEGAETH_TOKENS, parseUnits, parseEther } from '@megaflow-labs/sdk';

// fromPrivateKey() creates a fully connected client in one line
const client = MegaFlowClient.fromPrivateKey('0xYOUR_PRIVATE_KEY');

// Read on-chain state
const balance = await client.getTokenBalance(MEGAETH_TOKENS.WETH, client.address!);
const allowance = await client.getAllowance(USDC, client.address!, DEX_ROUTER);

// Build, simulate, and execute — all in one chain
const result = await client
  .batch()
  .safeApprove(USDC, DEX_ROUTER, parseUnits('100', 6), allowance)
  .swapExactTokensForTokens({
    router: DEX_ROUTER,
    amountIn: parseUnits('100', 6),
    amountOutMin: parseEther('0.03'),
    path: [USDC, MEGAETH_TOKENS.WETH],
    to: client.address!,
  })
  .executeSync(); // instant receipt on MegaETH (~10ms)

console.log(`Tx hash: ${result.receipt.transactionHash}`);
console.log(`Gas used: ${result.gasUsed}`);
```

> **Using an existing viem account or WalletClient?** Both still work:
> ```typescript
> import { MegaFlowClient, privateKeyToAccount } from '@megaflow-labs/sdk';
> const client = new MegaFlowClient().connectWithAccount(privateKeyToAccount('0x...'));
> // or: .connect(myExistingWalletClient)
> ```

---

## Core Concepts

### MegaFlowBuilder

Low-level builder for composing batches. All methods are chainable.

```typescript
import { MegaFlowBuilder } from '@megaflow-labs/sdk';

const builder = new MegaFlowBuilder();

// Chain as many operations as you need
builder
  .connect(walletClient)
  .wrapETH(MEGAETH_TOKENS.WETH, parseEther('0.1'))   // wrap ETH → WETH
  .transfer(MEGAETH_TOKENS.WETH, recipient, parseEther('0.1')); // send WETH

// Dry-run before broadcasting (no gas spent)
const sim = await builder.simulate();
if (!sim.success) throw new Error(sim.error);

// Execute — standard async flow
const result = await builder.execute();
```

### MegaFlowClient

Stateful high-level client. Extends MegaFlowBuilder with token reads, nonce management, and WebSocket support.

**Factory methods (v0.1.1+):**

```typescript
import { MegaFlowClient, parseUnits } from '@megaflow-labs/sdk';

// From private key
const client = MegaFlowClient.fromPrivateKey('0xYOUR_KEY');

// From mnemonic
const client2 = MegaFlowClient.fromMnemonic('word1 word2 ... word12');

// Batch transfers to multiple recipients in one tx
const result = await client
  .batch()
  .multiTransfer(USDC, [
    { to: '0xAlice...', amount: parseUnits('50', 6) },
    { to: '0xBob...', amount: parseUnits('50', 6) },
  ])
  .execute();
```

---

## What's re-exported from viem

You can import all of these directly from `@megaflow-labs/sdk` — **no separate `viem` install needed**:

| Category | Exports |
|---|---|
| **Account factories** | `privateKeyToAccount`, `mnemonicToAccount`, `hdKeyToAccount` |
| **Unit helpers** | `parseUnits`, `parseEther`, `formatUnits`, `formatEther` |
| **ABI helpers** | `parseAbi`, `parseAbiItem`, `parseAbiParameters` |
| **Client factories** | `createPublicClient`, `createWalletClient`, `http`, `webSocket` |
| **Address utilities** | `isAddress`, `getAddress`, `zeroAddress` |
| **Encoding** | `encodeFunctionData`, `decodeFunctionData`, `encodeAbiParameters`, `decodeAbiParameters` |
| **Types** | `Address`, `Hash`, `Hex`, `Chain`, `PublicClient`, `WalletClient`, `Account`, `TransactionReceipt` |

---

## API Reference

### Execution Methods

| Method | Description |
|--------|-------------|
| `execute(options?)` | Standard async flow: simulate → send → wait for receipt |
| `executeSync(options?)` | MegaETH sync flow: instant receipt in one RPC roundtrip |
| `executeRealtime(options?)` | Alternative realtime RPC endpoint |
| `simulate()` | Dry-run with no gas spent. Returns success/error/gasEstimate |

### ERC20 Helpers

| Method | Description |
|--------|-------------|
| `.approve(token, spender, amount)` | Single ERC20 approve |
| `.safeApprove(token, spender, amount, currentAllowance)` | Reset-then-approve (USDT-safe) |
| `.transfer(token, to, amount)` | ERC20 transfer |
| `.transferFrom(token, from, to, amount)` | ERC20 transferFrom |
| `.multiTransfer(token, [{to, amount}])` | Batch transfer to multiple recipients |

### DEX Helpers

| Method | Description |
|--------|-------------|
| `.swapExactTokensForTokens(params)` | Uniswap V2-compatible token→token swap |
| `.swapExactETHForTokens(params)` | ETH→token swap |
| `.swapExactTokensForETH(params)` | token→ETH swap |
| `.approveAndSwap(params)` | Approve + swap in one call |
| `.kyberSwap(params, sender)` | KyberSwap aggregator (async) |

### WETH Helpers

| Method | Description |
|--------|-------------|
| `.wrapETH(wethAddress, amount)` | Deposit ETH → WETH |
| `.unwrapWETH(wethAddress, amount)` | Withdraw WETH → ETH |

### ERC721 Helpers

| Method | Description |
|--------|-------------|
| `.transferNFT(nft, from, to, tokenId)` | safeTransferFrom |
| `.approveNFT(nft, to, tokenId)` | Approve single token |
| `.setApprovalForAll(nft, operator, approved)` | Operator approval |

### Utility Methods

| Method | Returns | Description |
|--------|---------|-------------|
| `getCalls()` | `MegaCall[]` | Current queued calls |
| `getTotalValue()` | `bigint` | Sum of ETH values |
| `getState()` | `BuilderState` | Full state snapshot |
| `summary()` | `string` | Human-readable batch description |
| `clear()` | `this` | Reset all calls |
| `pop()` | `MegaCall` | Remove last call |

### `ExecuteOptions`

```typescript
const result = await builder.execute({
  gasLimit: 300_000n,
  maxFeePerGas: parseGwei('0.001'),
  nonce: 42,
});
```

---

## Error Handling

```typescript
import { MegaFlowError } from '@megaflow-labs/sdk';

try {
  await builder.execute();
} catch (err) {
  if (err instanceof MegaFlowError) {
    switch (err.code) {
      case 'EMPTY_BATCH':       // No calls added
      case 'WALLET_NOT_CONNECTED': // connect() not called
      case 'SIMULATION_FAILED': // Dry-run failed
      case 'EXECUTION_FAILED':  // On-chain revert
      case 'USER_REJECTED':     // MetaMask rejected
    }
  }
}
```

---

## Debug Mode

```typescript
const builder = new MegaFlowBuilder({ debug: true });
// Logs to console: wallet connection, tx hash, gas used, sync timing
```

Print a readable summary before executing:

```typescript
builder
  .approve(USDC, DEX, amount)
  .swapExactTokensForTokens({ ... });

console.log(builder.summary());
// MegaFlow Batch (2 calls)
// Chain: MegaETH Mainnet (4326)
// Router: 0x9c1528e...
// Operations:
//   1. approve → 0x4200000...
//   2. swap    → 0xDEX_ADD...
```

---

## Network Configuration

```typescript
import { megaethMainnet, megaethTestnet } from '@megaflow-labs/sdk';

// Testnet (Carrot)
const client = new MegaFlowClient({ chain: megaethTestnet });

// Custom RPC
const client = new MegaFlowClient({ rpcUrl: 'https://your-rpc.example.com' });
```

---

## Examples

See the **[megaflow-labs/examples](https://github.com/megaflow-labs/examples)** repository for 14 working TypeScript scripts covering real DeFi patterns:

| Script | Pattern |
|---|---|
| `04-yield-optimizer` | Wrap + Approve + Supply to Aave in one tx |
| `05-leverage-loop` | Flashloan-style leverage loop without smart contracts |
| `06-nft-sweep-and-stake` | Buy NFT + stake atomically |
| `07-token-snipe-and-protect` | Snipe + stop-loss authorization |
| `08-bridge-intent` | Swap + bridge to L1 in one signature |
| `09-flash-arbitrage` | Zero-risk EOA arbitrage across two DEXes |
| `10-debt-repayment` | Liquidation rescue (swap illiquid → repay) |
| `11-airdrop-claim-and-sell` | Claim + sell before price collapses |
| `12-payroll-batch` | Treasury swap + pay 50 contributors |
| `13-portfolio-rebalance` | Multi-sell → single target buy |
| `14-options-payoff` | Conditional options exercise |

**Clone and run:**
```bash
git clone https://github.com/megaflow-labs/examples
cd examples && npm install
cp .env.example .env   # add your PRIVATE_KEY
npm run 04-yield
```

---

## Links

- **Website:** [megaflow.space](https://megaflow.space)
- **Examples:** [github.com/megaflow-labs/examples](https://github.com/megaflow-labs/examples)
- **GitHub:** [github.com/megaflow-labs](https://github.com/megaflow-labs)
- **NPM:** [@megaflow-labs/sdk](https://www.npmjs.com/package/@megaflow-labs/sdk)
- **AI Context:** [llms.txt](https://github.com/megaflow-labs/sdk/blob/main/llms.txt)

---

## License

MIT © [MegaFlow Labs](https://megaflow.space)