four-flap-meme-sdk 1.3.2 → 1.3.3

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.
@@ -34,7 +34,6 @@ export async function createTokenWithBundleBuyMerkle(params) {
34
34
  throw new Error(getErrorMessage('AMOUNT_MISMATCH', buyAmounts.length, privateKeys.length - 1));
35
35
  }
36
36
  const { provider, chainId } = createChainContext(chain, config.rpcUrl);
37
- const gasPrice = await resolveGasPrice(provider, config);
38
37
  const nonceManager = new NonceManager(provider);
39
38
  const signedTxs = [];
40
39
  const devWallet = new Wallet(privateKeys[0], provider);
@@ -42,8 +41,9 @@ export async function createTokenWithBundleBuyMerkle(params) {
42
41
  const originalPortalAddr = FLAP_ORIGINAL_PORTAL_ADDRESSES[chain];
43
42
  const portal = new ethers.Contract(originalPortalAddr, PORTAL_ABI, devWallet);
44
43
  const useV3 = !!params.extensionID;
45
- const createTxUnsigned = useV3
46
- ? await portal.newTokenV3.populateTransaction({
44
+ // 优化:并行获取 gasPrice、devWallet nonce 和 createTx
45
+ const createTxPromise = useV3
46
+ ? portal.newTokenV3.populateTransaction({
47
47
  name: tokenInfo.name,
48
48
  symbol: tokenInfo.symbol,
49
49
  meta: tokenInfo.meta,
@@ -58,7 +58,7 @@ export async function createTokenWithBundleBuyMerkle(params) {
58
58
  extensionID: params.extensionID,
59
59
  extensionData: params.extensionData ?? '0x'
60
60
  })
61
- : await portal.newTokenV2.populateTransaction({
61
+ : portal.newTokenV2.populateTransaction({
62
62
  name: tokenInfo.name,
63
63
  symbol: tokenInfo.symbol,
64
64
  meta: tokenInfo.meta,
@@ -71,10 +71,15 @@ export async function createTokenWithBundleBuyMerkle(params) {
71
71
  beneficiary: devWallet.address,
72
72
  permitData: '0x'
73
73
  });
74
+ const [gasPrice, createTxUnsigned, devNonce] = await Promise.all([
75
+ resolveGasPrice(provider, config),
76
+ createTxPromise,
77
+ nonceManager.getNextNonce(devWallet)
78
+ ]);
74
79
  const createTxRequest = {
75
80
  ...createTxUnsigned,
76
81
  from: devWallet.address,
77
- nonce: await nonceManager.getNextNonce(devWallet),
82
+ nonce: devNonce,
78
83
  gasLimit: getGasLimit(config),
79
84
  gasPrice,
80
85
  chainId,
@@ -99,8 +104,11 @@ export async function createTokenWithBundleBuyMerkle(params) {
99
104
  console.log('🔍 createToken SDK 精度转换: 18 -> ', params.quoteTokenDecimals, ', 原始:', fundsList, ', 转换后:', adjustedFundsList);
100
105
  }
101
106
  console.log('🔍 createToken SDK - quoteToken:', params.quoteToken, 'inputToken:', inputToken, 'useNativeToken:', useNativeToken);
102
- const unsignedBuys = await populateBuyTransactionsWithQuote(buyers, portalAddr, tokenAddress, adjustedFundsList, inputToken, useNativeToken);
103
- const buyerNonces = await allocateBuyerNonces(buyers, extractProfit, maxFundsIndex, totalProfit, nonceManager);
107
+ // 优化:并行获取 unsignedBuys buyerNonces
108
+ const [unsignedBuys, buyerNonces] = await Promise.all([
109
+ populateBuyTransactionsWithQuote(buyers, portalAddr, tokenAddress, adjustedFundsList, inputToken, useNativeToken),
110
+ allocateBuyerNonces(buyers, extractProfit, maxFundsIndex, totalProfit, nonceManager)
111
+ ]);
104
112
  const signedBuys = await signBuyTransactions({
105
113
  unsignedBuys,
106
114
  buyers,
@@ -170,12 +178,12 @@ export async function batchBuyWithBundleMerkle(params) {
170
178
  console.log('🔍 SDK inputToken 计算结果:', inputToken);
171
179
  console.log('🔍 SDK useNativeToken:', useNativeToken);
172
180
  console.log('🔍 SDK adjustedFundsList:', adjustedFundsList);
173
- // ✅ 优化:并行执行 gasPrice 和 populateBuyTransactions(最耗时的两个操作)
174
- const [gasPrice, unsignedBuys] = await Promise.all([
181
+ // ✅ 优化:并行执行 gasPrice、populateBuyTransactionsallocateBuyerNonces(三个最耗时的 RPC 操作)
182
+ const [gasPrice, unsignedBuys, buyerNonces] = await Promise.all([
175
183
  resolveGasPrice(provider, config),
176
- populateBuyTransactionsWithQuote(buyers, FLAP_PORTAL_ADDRESSES[chain], tokenAddress, adjustedFundsList, inputToken, useNativeToken)
184
+ populateBuyTransactionsWithQuote(buyers, FLAP_PORTAL_ADDRESSES[chain], tokenAddress, adjustedFundsList, inputToken, useNativeToken),
185
+ allocateBuyerNonces(buyers, extractProfit, maxFundsIndex, totalProfit, nonceManager)
177
186
  ]);
178
- const buyerNonces = await allocateBuyerNonces(buyers, extractProfit, maxFundsIndex, totalProfit, nonceManager);
179
187
  const signedBuys = await signBuyTransactions({
180
188
  unsignedBuys,
181
189
  buyers,
@@ -343,19 +351,23 @@ function buildGasLimitList(length, config) {
343
351
  const gasLimit = getGasLimit(config);
344
352
  return new Array(length).fill(gasLimit);
345
353
  }
354
+ /**
355
+ * ✅ 优化:并行获取所有钱包的 nonce
356
+ * 之前是串行循环,每个钱包一次 RPC 调用,非常慢
357
+ * 现在并行获取,大幅提升性能
358
+ */
346
359
  async function allocateBuyerNonces(buyers, extractProfit, maxIndex, totalProfit, nonceManager) {
347
- const nonces = [];
348
- for (let i = 0; i < buyers.length; i++) {
349
- if (extractProfit && totalProfit > 0n && i === maxIndex) {
350
- const [nonce] = await nonceManager.getNextNonceBatch(buyers[i], 2);
351
- nonces.push(nonce);
352
- }
353
- else {
354
- const nonce = await nonceManager.getNextNonce(buyers[i]);
355
- nonces.push(nonce);
356
- }
360
+ // 并行获取所有钱包的初始 nonce
361
+ const initialNonces = await Promise.all(buyers.map(buyer => nonceManager.getNextNonce(buyer)));
362
+ // 如果需要提取利润,maxIndex 钱包需要额外一个 nonce(用于利润转账)
363
+ // 但这里只返回买入交易的 nonce,利润交易的 nonce appendProfitTransaction 中处理
364
+ // NonceManager 内部会追踪已分配的 nonce
365
+ // 如果 maxIndex 钱包需要 2 个 nonce,提前预留
366
+ if (extractProfit && totalProfit > 0n && maxIndex >= 0 && maxIndex < buyers.length) {
367
+ // 再获取一个 nonce 给利润交易(NonceManager 内部会自增)
368
+ await nonceManager.getNextNonce(buyers[maxIndex]);
357
369
  }
358
- return nonces;
370
+ return initialNonces;
359
371
  }
360
372
  async function signBuyTransactions({ unsignedBuys, buyers, nonces, gasLimits, gasPrice, chainId, config, fundsList, useNativeToken = true // ✅ 默认使用原生代币
361
373
  }) {
@@ -0,0 +1,16 @@
1
+ /**
2
+ * ECDH + AES-GCM 加密工具(浏览器兼容)
3
+ * 用于将签名交易用服务器公钥加密
4
+ */
5
+ /**
6
+ * 用服务器公钥加密签名交易(ECDH + AES-GCM)
7
+ *
8
+ * @param signedTransactions 签名后的交易数组
9
+ * @param publicKeyBase64 服务器提供的公钥(Base64 格式)
10
+ * @returns JSON 字符串 {e: 临时公钥, i: IV, d: 密文}
11
+ */
12
+ export declare function encryptWithPublicKey(signedTransactions: string[], publicKeyBase64: string): Promise<string>;
13
+ /**
14
+ * 验证公钥格式(Base64)
15
+ */
16
+ export declare function validatePublicKey(publicKeyBase64: string): boolean;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * ECDH + AES-GCM 加密工具(浏览器兼容)
3
+ * 用于将签名交易用服务器公钥加密
4
+ */
5
+ /**
6
+ * 获取全局 crypto 对象(最简单直接的方式)
7
+ */
8
+ function getCryptoAPI() {
9
+ // 尝试所有可能的全局对象,优先浏览器环境
10
+ const cryptoObj = (typeof window !== 'undefined' && window.crypto) ||
11
+ (typeof self !== 'undefined' && self.crypto) ||
12
+ (typeof global !== 'undefined' && global.crypto) ||
13
+ (typeof globalThis !== 'undefined' && globalThis.crypto);
14
+ if (!cryptoObj) {
15
+ const env = typeof window !== 'undefined' ? 'Browser' : 'Node.js';
16
+ const protocol = typeof location !== 'undefined' ? location.protocol : 'unknown';
17
+ throw new Error(`❌ Crypto API 不可用。环境: ${env}, 协议: ${protocol}. ` +
18
+ '请确保在 HTTPS 或 localhost 下运行');
19
+ }
20
+ return cryptoObj;
21
+ }
22
+ /**
23
+ * 获取 SubtleCrypto(用于加密操作)
24
+ */
25
+ function getSubtleCrypto() {
26
+ const crypto = getCryptoAPI();
27
+ if (!crypto.subtle) {
28
+ const protocol = typeof location !== 'undefined' ? location.protocol : 'unknown';
29
+ const hostname = typeof location !== 'undefined' ? location.hostname : 'unknown';
30
+ throw new Error(`❌ SubtleCrypto API 不可用。协议: ${protocol}, 主机: ${hostname}. ` +
31
+ '请确保:1) 使用 HTTPS (或 localhost);2) 浏览器支持 Web Crypto API;' +
32
+ '3) 不在无痕/隐私浏览模式下');
33
+ }
34
+ return crypto.subtle;
35
+ }
36
+ /**
37
+ * Base64 转 ArrayBuffer(优先使用浏览器 API)
38
+ */
39
+ function base64ToArrayBuffer(base64) {
40
+ // 浏览器环境(优先)
41
+ if (typeof atob !== 'undefined') {
42
+ const binaryString = atob(base64);
43
+ const bytes = new Uint8Array(binaryString.length);
44
+ for (let i = 0; i < binaryString.length; i++) {
45
+ bytes[i] = binaryString.charCodeAt(i);
46
+ }
47
+ return bytes.buffer;
48
+ }
49
+ // Node.js 环境(fallback)
50
+ if (typeof Buffer !== 'undefined') {
51
+ return Buffer.from(base64, 'base64').buffer;
52
+ }
53
+ throw new Error('❌ Base64 解码不可用');
54
+ }
55
+ /**
56
+ * ArrayBuffer 转 Base64(优先使用浏览器 API)
57
+ */
58
+ function arrayBufferToBase64(buffer) {
59
+ // 浏览器环境(优先)
60
+ if (typeof btoa !== 'undefined') {
61
+ const bytes = new Uint8Array(buffer);
62
+ let binary = '';
63
+ for (let i = 0; i < bytes.length; i++) {
64
+ binary += String.fromCharCode(bytes[i]);
65
+ }
66
+ return btoa(binary);
67
+ }
68
+ // Node.js 环境(fallback)
69
+ if (typeof Buffer !== 'undefined') {
70
+ return Buffer.from(buffer).toString('base64');
71
+ }
72
+ throw new Error('❌ Base64 编码不可用');
73
+ }
74
+ /**
75
+ * 生成随机 Hex 字符串
76
+ */
77
+ function randomHex(length) {
78
+ const crypto = getCryptoAPI();
79
+ const array = new Uint8Array(length);
80
+ crypto.getRandomValues(array);
81
+ return Array.from(array)
82
+ .map(b => b.toString(16).padStart(2, '0'))
83
+ .join('');
84
+ }
85
+ /**
86
+ * 用服务器公钥加密签名交易(ECDH + AES-GCM)
87
+ *
88
+ * @param signedTransactions 签名后的交易数组
89
+ * @param publicKeyBase64 服务器提供的公钥(Base64 格式)
90
+ * @returns JSON 字符串 {e: 临时公钥, i: IV, d: 密文}
91
+ */
92
+ export async function encryptWithPublicKey(signedTransactions, publicKeyBase64) {
93
+ try {
94
+ // 0. 获取 SubtleCrypto 和 Crypto API
95
+ const subtle = getSubtleCrypto();
96
+ const crypto = getCryptoAPI();
97
+ // 1. 准备数据
98
+ const payload = {
99
+ signedTransactions,
100
+ timestamp: Date.now(),
101
+ nonce: randomHex(8)
102
+ };
103
+ const plaintext = JSON.stringify(payload);
104
+ // 2. 生成临时 ECDH 密钥对
105
+ const ephemeralKeyPair = await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveKey']);
106
+ // 3. 导入服务器公钥
107
+ const publicKeyBuffer = base64ToArrayBuffer(publicKeyBase64);
108
+ const publicKey = await subtle.importKey('raw', publicKeyBuffer, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
109
+ // 4. 派生共享密钥(AES-256)
110
+ const sharedKey = await subtle.deriveKey({ name: 'ECDH', public: publicKey }, ephemeralKeyPair.privateKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
111
+ // 5. AES-GCM 加密
112
+ const iv = crypto.getRandomValues(new Uint8Array(12));
113
+ const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, sharedKey, new TextEncoder().encode(plaintext));
114
+ // 6. 导出临时公钥
115
+ const ephemeralPublicKeyRaw = await subtle.exportKey('raw', ephemeralKeyPair.publicKey);
116
+ // 7. 返回加密包(JSON 格式)
117
+ return JSON.stringify({
118
+ e: arrayBufferToBase64(ephemeralPublicKeyRaw), // 临时公钥
119
+ i: arrayBufferToBase64(iv.buffer), // IV
120
+ d: arrayBufferToBase64(encrypted) // 密文
121
+ });
122
+ }
123
+ catch (error) {
124
+ throw new Error(`加密失败: ${error?.message || String(error)}`);
125
+ }
126
+ }
127
+ /**
128
+ * 验证公钥格式(Base64)
129
+ */
130
+ export function validatePublicKey(publicKeyBase64) {
131
+ try {
132
+ if (!publicKeyBase64)
133
+ return false;
134
+ // Base64 字符集验证
135
+ if (!/^[A-Za-z0-9+/=]+$/.test(publicKeyBase64))
136
+ return false;
137
+ // ECDH P-256 公钥固定长度 65 字节(未压缩)
138
+ // Base64 编码后约 88 字符
139
+ if (publicKeyBase64.length < 80 || publicKeyBase64.length > 100)
140
+ return false;
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "four-flap-meme-sdk",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "description": "SDK for Flap bonding curve and four.meme TokenManager",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",