npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@megaflow-labs/sdk

v0.1.2

Published

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

Readme

@megaflow-labs/sdk

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

npm License: MIT TypeScript


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

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

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:

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.

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+):

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/sdkno 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

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

Error Handling

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

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

Print a readable summary before executing:

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

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 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:

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


License

MIT © MegaFlow Labs