four-flap-meme-sdk 4.5.5 → 4.5.6

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.
@@ -3,6 +3,24 @@
3
3
  */
4
4
  import { ethers, Wallet } from 'ethers';
5
5
  import type { MultiSwapTxParams, MultiSwapUnsignedResult, RouteParams } from './bundle-buy-first-types.js';
6
+ /**
7
+ * 买方计价币、卖方代币对当前 Router 的授权不够时,签同包 approve(换了 DEX 后旧授权不算数)。
8
+ * nonce 从 noncesMap 取并原地顺延,调用方之后再分配买卖 nonce。
9
+ */
10
+ export declare function signRouterApprovals(params: {
11
+ provider: ethers.JsonRpcProvider;
12
+ routeParams: RouteParams;
13
+ v2RouterAddress?: string;
14
+ useNativeToken: boolean;
15
+ buyers: Wallet[];
16
+ buyAmounts: bigint[];
17
+ sellers: Wallet[];
18
+ sellAmounts: bigint[];
19
+ noncesMap: Map<string, number>;
20
+ gasPrice: bigint;
21
+ chainId: number;
22
+ txType: number;
23
+ }): Promise<string[]>;
6
24
  /**
7
25
  * ✅ 构建多笔买入和卖出交易
8
26
  */
@@ -4,6 +4,53 @@
4
4
  import { ethers, Contract } from 'ethers';
5
5
  import { getDeadline } from '../../../utils/bundle-helpers.js';
6
6
  import { FLAT_FEE, PANCAKE_V2_ROUTER_ABI, PANCAKE_V2_ROUTER_ADDRESS, PANCAKE_V3_ROUTER_ABI, PANCAKE_V3_ROUTER_ADDRESS, } from './bundle-buy-first-constants.js';
7
+ import { ERC20_ABI } from '../../../abis/common.js';
8
+ import { signMissingAllowanceApprovals } from '../../../domains/dex/direct-router-approvals.js';
9
+ /**
10
+ * 买方计价币、卖方代币对当前 Router 的授权不够时,签同包 approve(换了 DEX 后旧授权不算数)。
11
+ * nonce 从 noncesMap 取并原地顺延,调用方之后再分配买卖 nonce。
12
+ */
13
+ export async function signRouterApprovals(params) {
14
+ const { routeParams } = params;
15
+ if (routeParams.routeType === 'v3-multi')
16
+ return [];
17
+ const spender = routeParams.routeType === 'v2' ? params.v2RouterAddress || PANCAKE_V2_ROUTER_ADDRESS : PANCAKE_V3_ROUTER_ADDRESS;
18
+ const [quoteToken, token] = routeParams.routeType === 'v2'
19
+ ? [routeParams.v2Path[0], routeParams.v2Path[routeParams.v2Path.length - 1]]
20
+ : [routeParams.v3TokenIn, routeParams.v3TokenOut];
21
+ const groups = [];
22
+ if (!params.useNativeToken)
23
+ groups.push({ tokenAddress: quoteToken, wallets: params.buyers, amounts: params.buyAmounts });
24
+ groups.push({ tokenAddress: token, wallets: params.sellers, amounts: params.sellAmounts });
25
+ const txs = [];
26
+ for (const group of groups) {
27
+ const erc20 = new Contract(group.tokenAddress, ERC20_ABI, params.provider);
28
+ const allowances = await Promise.all(group.wallets.map((w) => erc20.allowance(w.address, spender).catch(() => ethers.MaxUint256)));
29
+ // 同一钱包出现多次时按合计额度判断,只授权一次
30
+ const merged = new Map();
31
+ group.wallets.forEach((wallet, i) => {
32
+ const key = wallet.address.toLowerCase();
33
+ const prev = merged.get(key);
34
+ merged.set(key, { wallet, amount: (prev?.amount ?? 0n) + (group.amounts[i] ?? 0n), allowance: allowances[i] });
35
+ });
36
+ const rows = [...merged.values()];
37
+ const nonces = rows.map((r) => params.noncesMap.get(r.wallet.address.toLowerCase()));
38
+ txs.push(...(await signMissingAllowanceApprovals({
39
+ provider: params.provider,
40
+ wallets: rows.map((r) => r.wallet),
41
+ nonces,
42
+ tokenAddress: group.tokenAddress,
43
+ spender,
44
+ amounts: rows.map((r) => r.amount),
45
+ allowances: rows.map((r) => r.allowance),
46
+ txType: params.txType,
47
+ gasPrice: params.gasPrice,
48
+ chainId: params.chainId,
49
+ })));
50
+ rows.forEach((r, i) => params.noncesMap.set(r.wallet.address.toLowerCase(), nonces[i]));
51
+ }
52
+ return txs;
53
+ }
7
54
  /**
8
55
  * ✅ 构建多笔买入和卖出交易
9
56
  */
@@ -0,0 +1,66 @@
1
+ import { ethers } from 'ethers';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { signRouterApprovals } from './bundle-buy-first-build.js';
4
+ const TOKEN = '0x3240179d0304215b88422e134bf931549f2b07ae';
5
+ const USDT = '0x55d398326f99059fF775485246999027B3197955';
6
+ const ROUTER = '0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24';
7
+ const MNEMONIC = 'test test test test test test test test test test test junk';
8
+ const wallet = (i) => ethers.HDNodeWallet.fromPhrase(MNEMONIC, undefined, `m/44'/60'/0'/0/${i}`);
9
+ const erc20 = new ethers.Interface(['function approve(address,uint256)']);
10
+ function mockAllowance(allowance) {
11
+ vi.spyOn(ethers.JsonRpcProvider.prototype, 'call').mockResolvedValue(ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [allowance]));
12
+ vi.spyOn(ethers.JsonRpcProvider.prototype, 'estimateGas').mockResolvedValue(50000n);
13
+ }
14
+ const run = (opts) => signRouterApprovals({
15
+ provider: new ethers.JsonRpcProvider('http://127.0.0.1:8545', 56, { staticNetwork: true }),
16
+ routeParams: { routeType: 'v2', v2Path: [USDT, TOKEN] },
17
+ v2RouterAddress: ROUTER,
18
+ useNativeToken: opts.useNativeToken,
19
+ buyers: opts.buyers,
20
+ buyAmounts: opts.buyers.map(() => 10n ** 18n),
21
+ sellers: opts.sellers,
22
+ sellAmounts: opts.sellers.map(() => 10n ** 18n),
23
+ noncesMap: opts.noncesMap,
24
+ gasPrice: 50000000n,
25
+ chainId: 56,
26
+ txType: 0,
27
+ }).then((txs) => txs.map((raw) => ethers.Transaction.from(raw)));
28
+ describe('signRouterApprovals', () => {
29
+ afterEach(() => vi.restoreAllMocks());
30
+ it('额度为 0:买方补计价币授权、卖方补代币授权,nonce 顺延', async () => {
31
+ mockAllowance(0n);
32
+ const [b1, b2, s1] = [wallet(1), wallet(2), wallet(3)];
33
+ const noncesMap = new Map([
34
+ [b1.address.toLowerCase(), 4],
35
+ [b2.address.toLowerCase(), 7],
36
+ [s1.address.toLowerCase(), 9],
37
+ ]);
38
+ const txs = await run({ useNativeToken: false, buyers: [b1, b2], sellers: [s1], noncesMap });
39
+ expect(txs.map((tx) => [tx.from, tx.to?.toLowerCase(), tx.nonce])).toEqual([
40
+ [b1.address, USDT.toLowerCase(), 4],
41
+ [b2.address, USDT.toLowerCase(), 7],
42
+ [s1.address, TOKEN, 9],
43
+ ]);
44
+ for (const tx of txs)
45
+ expect(erc20.decodeFunctionData('approve', tx.data)[0]).toBe(ROUTER);
46
+ expect([...noncesMap.values()]).toEqual([5, 8, 10]);
47
+ });
48
+ it('已授权时不补,nonce 不动', async () => {
49
+ mockAllowance(ethers.MaxUint256);
50
+ const [b1, s1] = [wallet(1), wallet(3)];
51
+ const noncesMap = new Map([
52
+ [b1.address.toLowerCase(), 4],
53
+ [s1.address.toLowerCase(), 9],
54
+ ]);
55
+ expect(await run({ useNativeToken: false, buyers: [b1], sellers: [s1], noncesMap })).toEqual([]);
56
+ expect([...noncesMap.values()]).toEqual([4, 9]);
57
+ });
58
+ it('BNB 计价时买方不需要授权;同一钱包买卖只顺延一次 nonce 链', async () => {
59
+ mockAllowance(0n);
60
+ const same = wallet(5);
61
+ const noncesMap = new Map([[same.address.toLowerCase(), 2]]);
62
+ const txs = await run({ useNativeToken: true, buyers: [same], sellers: [same, same], noncesMap });
63
+ expect(txs.map((tx) => [tx.to?.toLowerCase(), tx.nonce])).toEqual([[TOKEN, 2]]);
64
+ expect(noncesMap.get(same.address.toLowerCase())).toBe(3);
65
+ });
66
+ });
@@ -9,7 +9,7 @@ import { quoteRoundTripProfitToNative } from '../../../core/quote/quote-helpers.
9
9
  import { splitAmountByWeight as splitAmount } from '../../../core/amount/split-by-weight.js';
10
10
  import { createPancakeContext, getGasPrice, planSequentialBuyFirstAmounts } from './bundle-buy-first-quote.js';
11
11
  import { validateSwapCounts } from './bundle-buy-first-plan.js';
12
- import { buildSingleBuyTx, buildSingleSellTx } from './bundle-buy-first-build.js';
12
+ import { buildSingleBuyTx, buildSingleSellTx, signRouterApprovals } from './bundle-buy-first-build.js';
13
13
  import { buildProfitTransaction } from './bundle-buy-first-profit.js';
14
14
  import { isSameWalletBuySell } from './quote.js';
15
15
  /**
@@ -114,6 +114,21 @@ export async function pancakeBundleBuyFirstMultiWallet(params) {
114
114
  type: txType,
115
115
  });
116
116
  }
117
+ // 授权不够的钱包同包补 approve(排在贿赂之后、买卖之前,nonce 顺延)
118
+ const approveTxs = await signRouterApprovals({
119
+ provider: context.provider,
120
+ routeParams,
121
+ v2RouterAddress: config.v2RouterAddress,
122
+ useNativeToken,
123
+ buyers,
124
+ buyAmounts: buyAmountsWei,
125
+ sellers,
126
+ sellAmounts: sellAmountsWei,
127
+ noncesMap,
128
+ gasPrice,
129
+ chainId: context.chainId,
130
+ txType,
131
+ });
117
132
  // 2. 预分配所有 nonces(同步操作,避免竞态)
118
133
  const buyerNonces = [];
119
134
  const sellerNonces = [];
@@ -177,10 +192,10 @@ export async function pancakeBundleBuyFirstMultiWallet(params) {
177
192
  Promise.all(buyTxPromises),
178
193
  Promise.all(sellTxPromises),
179
194
  ]);
180
- // 组装交易顺序:贿赂 → 买入 → 卖出
195
+ // 组装交易顺序:贿赂 → 授权 → 买入 → 卖出
181
196
  if (bribeTx)
182
197
  allTransactions.push(bribeTx);
183
- allTransactions.push(...signedBuys, ...signedSells);
198
+ allTransactions.push(...approveTxs, ...signedBuys, ...signedSells);
184
199
  // 5. 利润多跳转账(由主卖方支付)
185
200
  let profitHopWallets;
186
201
  if (profitAmount > 0n) {
@@ -6,7 +6,7 @@ import { getGasLimit } from '../../../core/gas/bundle-gas.js';
6
6
  import { NonceManager } from '../../../utils/bundle-helpers.js';
7
7
  import { BLOCKRAZOR_BUILDER_EOA, ZERO_ADDRESS, GAS_LIMITS, calculateBundleSwapRoundTripProfit } from '../../../core/constants/index.js';
8
8
  import { quoteRoundTripProfitToNative } from '../../../core/quote/quote-helpers.js';
9
- import { buildMultiRouteTransactions, buildProfitTransaction, calculateBuyerFunds, createPancakeContext, getGasPrice, pancakeBundleBuyFirstMultiWallet, planMultiNonces, planSequentialBuyFirstAmounts, splitAmount, validateFinalBalances, validateSwapCounts, } from './bundle-buy-first-helpers.js';
9
+ import { buildMultiRouteTransactions, signRouterApprovals, buildProfitTransaction, calculateBuyerFunds, createPancakeContext, getGasPrice, pancakeBundleBuyFirstMultiWallet, planMultiNonces, planSequentialBuyFirstAmounts, splitAmount, validateFinalBalances, validateSwapCounts, } from './bundle-buy-first-helpers.js';
10
10
  export async function pancakeBundleBuyFirstMerkle(params) {
11
11
  const { buyerPrivateKey, buyerPrivateKeys, sellerPrivateKey, sellerPrivateKeys, routeParams, buyerFunds, buyerFundsPercentage, config, quoteToken, quoteTokenDecimals = 18, buyCount: _buyCount, sellCount: _sellCount, taxRateBps = 0, // ✅ 税率(基点),用于计算实际可卖出代币数量
12
12
  } = params;
@@ -116,6 +116,34 @@ export async function pancakeBundleBuyFirstMerkle(params) {
116
116
  type: txType,
117
117
  });
118
118
  }
119
+ // 授权不够时同包补 approve:从贿赂后的第一个 nonce 开始签,该钱包后续 nonce 整体顺延
120
+ const buyerAddr = buyer.address.toLowerCase();
121
+ const sellerAddr = seller.address.toLowerCase();
122
+ const approveStart = new Map([[buyerAddr, multiNoncePlan.buyerNonces[0]]]);
123
+ if (!sameAddress)
124
+ approveStart.set(sellerAddr, multiNoncePlan.sellerNonces[0]);
125
+ const approveNonces = new Map(approveStart);
126
+ const approveTxs = await signRouterApprovals({
127
+ provider: context.provider,
128
+ routeParams,
129
+ v2RouterAddress: config.v2RouterAddress,
130
+ useNativeToken,
131
+ buyers: [buyer],
132
+ buyAmounts: [buyerFundsInfo.buyerFundsWei],
133
+ sellers: [seller],
134
+ sellAmounts: [sellAmountsWei.reduce((sum, a) => sum + a, 0n)],
135
+ noncesMap: approveNonces,
136
+ gasPrice,
137
+ chainId: context.chainId,
138
+ txType,
139
+ });
140
+ const shiftOf = (addr) => approveNonces.get(addr) - approveStart.get(addr);
141
+ const buyerShift = shiftOf(buyerAddr);
142
+ const sellerShift = sameAddress ? buyerShift : shiftOf(sellerAddr);
143
+ multiNoncePlan.buyerNonces = multiNoncePlan.buyerNonces.map((n) => n + buyerShift);
144
+ multiNoncePlan.sellerNonces = multiNoncePlan.sellerNonces.map((n) => n + sellerShift);
145
+ if (multiNoncePlan.profitNonce !== undefined)
146
+ multiNoncePlan.profitNonce += sellerShift;
119
147
  // ✅ 并行签名所有买入交易
120
148
  const signedBuys = await Promise.all(swapUnsignedArray.buyUnsignedArray.map((unsigned, i) => buyer.signTransaction({
121
149
  ...unsigned,
@@ -150,11 +178,11 @@ export async function pancakeBundleBuyFirstMerkle(params) {
150
178
  buyerAddress: buyer.address,
151
179
  nativeBalance: buyerFundsInfo.nativeBalance,
152
180
  });
153
- // ✅ 组装顺序:贿赂 → 买入(多笔) → 卖出(多笔)(与 Flap 一致)
181
+ // ✅ 组装顺序:贿赂 → 授权(按需) → 买入(多笔) → 卖出(多笔)
154
182
  const allTransactions = [];
155
183
  if (bribeTx)
156
184
  allTransactions.push(bribeTx);
157
- allTransactions.push(...signedBuys, ...signedSells);
185
+ allTransactions.push(...approveTxs, ...signedBuys, ...signedSells);
158
186
  // ✅ 利润多跳转账(强制 2 跳中转)
159
187
  const profitResult = await buildProfitTransaction({
160
188
  provider: context.provider,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "four-flap-meme-sdk",
3
- "version": "4.5.5",
3
+ "version": "4.5.6",
4
4
  "description": "SDK for Flap bonding curve and four.meme TokenManager",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",