@megaflow-labs/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,47 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@megaflow-labs/sdk` will be documented in this file.
4
+
5
+ This project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ---
8
+
9
+ ## [0.1.0] – 2026-02-26
10
+
11
+ ### Initial release
12
+
13
+ #### Core
14
+ - `MegaFlowBuilder` — chainable batch transaction builder
15
+ - `MegaFlowClient` — stateful high-level client with nonce management and WebSocket support
16
+ - `MegaRouter` contract integration with atomic batch execution
17
+
18
+ #### Operations
19
+ - ERC20: `approve`, `safeApprove` (reset-then-approve), `transfer`, `transferFrom`, `multiTransfer`
20
+ - WETH: `wrapETH`, `unwrapWETH`
21
+ - DEX: `swapExactTokensForTokens`, `swapExactETHForTokens`, `swapExactTokensForETH`, `approveAndSwap`
22
+ - ERC721: `transferNFT`, `approveNFT`, `setApprovalForAll`
23
+ - KyberSwap aggregator integration: `kyberSwap`
24
+ - Generic: `add`, `addCall`, `sendETH`
25
+
26
+ #### Execution
27
+ - `execute()` — standard async flow (simulate → send → waitForReceipt)
28
+ - `executeSync()` — MegaETH `eth_sendRawTransactionSync` (EIP-7966), instant receipt
29
+ - `executeRealtime()` — `realtime_sendRawTransaction` endpoint
30
+ - `simulate()` — dry-run with no gas spent, returns per-call results and gas estimate
31
+ - `ExecuteOptions` — gas limit, maxFeePerGas, nonce overrides
32
+
33
+ #### Debugging & Introspection
34
+ - `debug` mode — structured console logs on wallet connect, tx send, gas used, sync timing
35
+ - `summary()` — human-readable batch description
36
+ - `getState()` / `getOperations()` — full builder snapshot for serialization
37
+ - `pop()` — undo last queued call
38
+
39
+ #### Error Handling
40
+ - `MegaFlowError` with typed `MegaFlowErrorCode` union
41
+ - `decodeRevertError` — decodes `Error(string)`, `Panic`, and MegaRouter custom errors
42
+ - Nested `CallFailed` inner revert decoding
43
+
44
+ #### Chains & Constants
45
+ - `megaethMainnet` and `megaethTestnet` chain definitions
46
+ - `MEGAETH_TOKENS` (WETH, MEGA, USDM), `MEGAETH_L1_BRIDGE`
47
+ - Bundled ABIs: `ERC20_ABI`, `ERC721_ABI`, `WETH_ABI`, `UNISWAP_V2_ROUTER_ABI`, `MEGA_ROUTER_ABI`
package/README.md ADDED
@@ -0,0 +1,259 @@
1
+ # @megaflow-labs/sdk
2
+
3
+ **Batch transaction SDK for MegaETH** — compose, simulate and execute multiple on-chain operations in a single atomic transaction.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@megaflow-labs/sdk)](https://www.npmjs.com/package/@megaflow-labs/sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)](https://www.typescriptlang.org/)
8
+
9
+ ---
10
+
11
+ ## Why MegaFlow?
12
+
13
+ On standard EVM chains, sending multiple transactions requires multiple wallet confirmations and multiple block waits. MegaFlow solves this:
14
+
15
+ | | Without MegaFlow | With MegaFlow |
16
+ |---|---|---|
17
+ | Approve + Swap | 2 wallet popups, 2 blocks | **1 wallet popup, 1 block** |
18
+ | Failure safety | First tx may succeed, second may fail | **All-or-nothing (atomic)** |
19
+ | Code complexity | ABI encoding, fee math, polling | **Chainable one-liners** |
20
+
21
+ ---
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install @megaflow-labs/sdk
27
+ ```
28
+
29
+ > Requires `viem ^2.0.0` (peer dependency) and Node.js ≥ 18.
30
+
31
+ ---
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import { MegaFlowClient, MEGAETH_TOKENS } from '@megaflow-labs/sdk';
37
+ import { privateKeyToAccount } from 'viem/accounts';
38
+ import { parseUnits, parseEther } from 'viem';
39
+
40
+ const account = privateKeyToAccount('0xYOUR_PRIVATE_KEY');
41
+
42
+ // Zero-config: connects to MegaETH Mainnet automatically
43
+ const client = new MegaFlowClient().connectWithAccount(account);
44
+
45
+ // Read on-chain state
46
+ const balance = await client.getTokenBalance(MEGAETH_TOKENS.WETH, account.address);
47
+ const allowance = await client.getAllowance(USDC, account.address, DEX_ROUTER);
48
+
49
+ // Build, simulate, and execute — all in one chain
50
+ const result = await client
51
+ .batch()
52
+ .safeApprove(USDC, DEX_ROUTER, parseUnits('100', 6), allowance)
53
+ .swapExactTokensForTokens({
54
+ router: DEX_ROUTER,
55
+ amountIn: parseUnits('100', 6),
56
+ amountOutMin: parseEther('0.03'),
57
+ path: [USDC, MEGAETH_TOKENS.WETH],
58
+ to: account.address,
59
+ })
60
+ .executeSync(); // instant receipt on MegaETH (~10ms)
61
+
62
+ console.log(`Tx hash: ${result.receipt.transactionHash}`);
63
+ console.log(`Gas used: ${result.gasUsed}`);
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Core Concepts
69
+
70
+ ### MegaFlowBuilder
71
+
72
+ Low-level builder for composing batches. All methods are chainable.
73
+
74
+ ```typescript
75
+ import { MegaFlowBuilder } from '@megaflow-labs/sdk';
76
+
77
+ const builder = new MegaFlowBuilder();
78
+
79
+ // Chain as many operations as you need
80
+ builder
81
+ .connect(walletClient)
82
+ .wrapETH(MEGAETH_TOKENS.WETH, parseEther('0.1')) // wrap ETH → WETH
83
+ .transfer(MEGAETH_TOKENS.WETH, recipient, parseEther('0.1')); // send WETH
84
+
85
+ // Dry-run before broadcasting (no gas spent)
86
+ const sim = await builder.simulate();
87
+ if (!sim.success) throw new Error(sim.error);
88
+
89
+ // Execute — standard async flow
90
+ const result = await builder.execute();
91
+ ```
92
+
93
+ ### MegaFlowClient
94
+
95
+ Stateful high-level client. Extends MegaFlowBuilder with token reads, nonce management, and WebSocket support.
96
+
97
+ ```typescript
98
+ import { MegaFlowClient } from '@megaflow-labs/sdk';
99
+
100
+ const client = new MegaFlowClient({ debug: true });
101
+ client.connectWithAccount(account);
102
+
103
+ // Read token state
104
+ const bal = await client.getTokenBalance(token, address);
105
+ const allowance = await client.getAllowance(token, address, spender);
106
+
107
+ // Batch transfers to multiple recipients in one tx
108
+ const result = await client
109
+ .batch()
110
+ .multiTransfer(USDC, [
111
+ { to: '0xAlice...', amount: parseUnits('50', 6) },
112
+ { to: '0xBob...', amount: parseUnits('50', 6) },
113
+ ])
114
+ .execute();
115
+ ```
116
+
117
+ ---
118
+
119
+ ## API Reference
120
+
121
+ ### Execution Methods
122
+
123
+ | Method | Description |
124
+ |--------|-------------|
125
+ | `execute(options?)` | Standard async flow: simulate → send → wait for receipt |
126
+ | `executeSync(options?)` | MegaETH sync flow: instant receipt in one RPC roundtrip |
127
+ | `executeRealtime(options?)` | Alternative realtime RPC endpoint |
128
+ | `simulate()` | Dry-run with no gas spent. Returns success/error/gasEstimate |
129
+
130
+ ### ERC20 Helpers
131
+
132
+ | Method | Description |
133
+ |--------|-------------|
134
+ | `.approve(token, spender, amount)` | Single ERC20 approve |
135
+ | `.safeApprove(token, spender, amount, currentAllowance)` | Reset-then-approve (USDT-safe) |
136
+ | `.transfer(token, to, amount)` | ERC20 transfer |
137
+ | `.transferFrom(token, from, to, amount)` | ERC20 transferFrom |
138
+ | `.multiTransfer(token, [{to, amount}])` | Batch transfer to multiple recipients |
139
+
140
+ ### DEX Helpers
141
+
142
+ | Method | Description |
143
+ |--------|-------------|
144
+ | `.swapExactTokensForTokens(params)` | Uniswap V2-compatible token→token swap |
145
+ | `.swapExactETHForTokens(params)` | ETH→token swap |
146
+ | `.swapExactTokensForETH(params)` | token→ETH swap |
147
+ | `.approveAndSwap(params)` | Approve + swap in one call |
148
+ | `.kyberSwap(params, sender)` | KyberSwap aggregator (async) |
149
+
150
+ ### WETH Helpers
151
+
152
+ | Method | Description |
153
+ |--------|-------------|
154
+ | `.wrapETH(wethAddress, amount)` | Deposit ETH → WETH |
155
+ | `.unwrapWETH(wethAddress, amount)` | Withdraw WETH → ETH |
156
+
157
+ ### ERC721 Helpers
158
+
159
+ | Method | Description |
160
+ |--------|-------------|
161
+ | `.transferNFT(nft, from, to, tokenId)` | safeTransferFrom |
162
+ | `.approveNFT(nft, to, tokenId)` | Approve single token |
163
+ | `.setApprovalForAll(nft, operator, approved)` | Operator approval |
164
+
165
+ ### Utility Methods
166
+
167
+ | Method | Returns | Description |
168
+ |--------|---------|-------------|
169
+ | `getCalls()` | `MegaCall[]` | Current queued calls |
170
+ | `getTotalValue()` | `bigint` | Sum of ETH values |
171
+ | `getState()` | `BuilderState` | Full state snapshot |
172
+ | `summary()` | `string` | Human-readable batch description |
173
+ | `clear()` | `this` | Reset all calls |
174
+ | `pop()` | `MegaCall` | Remove last call |
175
+
176
+ ### `ExecuteOptions`
177
+
178
+ ```typescript
179
+ const result = await builder.execute({
180
+ gasLimit: 300_000n,
181
+ maxFeePerGas: parseGwei('0.001'),
182
+ nonce: 42,
183
+ });
184
+ ```
185
+
186
+ ---
187
+
188
+ ## Error Handling
189
+
190
+ ```typescript
191
+ import { MegaFlowError } from '@megaflow-labs/sdk';
192
+
193
+ try {
194
+ await builder.execute();
195
+ } catch (err) {
196
+ if (err instanceof MegaFlowError) {
197
+ switch (err.code) {
198
+ case 'EMPTY_BATCH': // No calls added
199
+ case 'WALLET_NOT_CONNECTED': // connect() not called
200
+ case 'SIMULATION_FAILED': // Dry-run failed
201
+ case 'EXECUTION_FAILED': // On-chain revert
202
+ case 'USER_REJECTED': // MetaMask rejected
203
+ }
204
+ }
205
+ }
206
+ ```
207
+
208
+ ---
209
+
210
+ ## Debug Mode
211
+
212
+ ```typescript
213
+ const builder = new MegaFlowBuilder({ debug: true });
214
+ // Logs to console: wallet connection, tx hash, gas used, sync timing
215
+ ```
216
+
217
+ Print a readable summary before executing:
218
+
219
+ ```typescript
220
+ builder
221
+ .approve(USDC, DEX, amount)
222
+ .swapExactTokensForTokens({ ... });
223
+
224
+ console.log(builder.summary());
225
+ // MegaFlow Batch (2 calls)
226
+ // Chain: MegaETH Mainnet (4326)
227
+ // Router: 0x9c1528e...
228
+ // Operations:
229
+ // 1. approve → 0x4200000...
230
+ // 2. swap → 0xDEX_ADD...
231
+ ```
232
+
233
+ ---
234
+
235
+ ## Network Configuration
236
+
237
+ ```typescript
238
+ import { megaethMainnet, megaethTestnet } from '@megaflow-labs/sdk';
239
+
240
+ // Testnet (Carrot)
241
+ const client = new MegaFlowClient({ chain: megaethTestnet });
242
+
243
+ // Custom RPC
244
+ const client = new MegaFlowClient({ rpcUrl: 'https://your-rpc.example.com' });
245
+ ```
246
+
247
+ ---
248
+
249
+ ## Links
250
+
251
+ - **Website:** [megaflow.space](https://megaflow.space)
252
+ - **GitHub:** [github.com/megaflow-labs](https://github.com/megaflow-labs)
253
+ - **NPM:** [@megaflow-labs/sdk](https://www.npmjs.com/package/@megaflow-labs/sdk)
254
+
255
+ ---
256
+
257
+ ## License
258
+
259
+ MIT © [MegaFlow Labs](https://megaflow.space)