@aastar/sdk 0.18.0 → 0.20.1

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.
Files changed (105) hide show
  1. package/LICENSE +180 -21
  2. package/dist/UserClient-YUHCJJJL.js +6 -0
  3. package/dist/UserClient-YUHCJJJL.js.map +1 -0
  4. package/dist/account.d.ts +1 -0
  5. package/dist/account.js +6 -0
  6. package/dist/account.js.map +1 -0
  7. package/dist/admin.d.ts +1 -0
  8. package/dist/admin.js +6 -0
  9. package/dist/admin.js.map +1 -0
  10. package/dist/airaccount.d.ts +2 -0
  11. package/dist/airaccount.js +4501 -0
  12. package/dist/airaccount.js.map +1 -0
  13. package/dist/channel.d.ts +1 -0
  14. package/dist/channel.js +6 -0
  15. package/dist/channel.js.map +1 -0
  16. package/dist/chunk-4DVUM4MC.js +106 -0
  17. package/dist/chunk-4DVUM4MC.js.map +1 -0
  18. package/dist/chunk-4KRQXOTI.js +4421 -0
  19. package/dist/chunk-4KRQXOTI.js.map +1 -0
  20. package/dist/chunk-6JCYPTSH.js +281 -0
  21. package/dist/chunk-6JCYPTSH.js.map +1 -0
  22. package/dist/chunk-DI3E6PMI.js +426 -0
  23. package/dist/chunk-DI3E6PMI.js.map +1 -0
  24. package/dist/chunk-DSZ372PH.js +333 -0
  25. package/dist/chunk-DSZ372PH.js.map +1 -0
  26. package/dist/chunk-HVAB4TTT.js +116 -0
  27. package/dist/chunk-HVAB4TTT.js.map +1 -0
  28. package/dist/chunk-MPOMWT2J.js +1140 -0
  29. package/dist/chunk-MPOMWT2J.js.map +1 -0
  30. package/dist/chunk-NZGXB2C5.js +115 -0
  31. package/dist/chunk-NZGXB2C5.js.map +1 -0
  32. package/dist/chunk-O3Y7II3B.js +578 -0
  33. package/dist/chunk-O3Y7II3B.js.map +1 -0
  34. package/dist/chunk-OSPRJZ5T.js +113 -0
  35. package/dist/chunk-OSPRJZ5T.js.map +1 -0
  36. package/dist/chunk-PCLPYRTX.js +229 -0
  37. package/dist/chunk-PCLPYRTX.js.map +1 -0
  38. package/dist/chunk-PZ5AY32C.js +9 -0
  39. package/dist/chunk-PZ5AY32C.js.map +1 -0
  40. package/dist/chunk-XFI3AK32.js +416 -0
  41. package/dist/chunk-XFI3AK32.js.map +1 -0
  42. package/dist/chunk-YHM77LIP.js +432 -0
  43. package/dist/chunk-YHM77LIP.js.map +1 -0
  44. package/dist/chunk-ZSSNU3UF.js +42091 -0
  45. package/dist/chunk-ZSSNU3UF.js.map +1 -0
  46. package/dist/contract-addresses-JE3X6DFY.js +4 -0
  47. package/dist/contract-addresses-JE3X6DFY.js.map +1 -0
  48. package/dist/core.d.ts +13 -0
  49. package/dist/core.js +5 -0
  50. package/dist/core.js.map +1 -0
  51. package/dist/dapp.d.ts +1 -0
  52. package/dist/dapp.js +7 -0
  53. package/dist/dapp.js.map +1 -0
  54. package/dist/dist-GHTBO7CD.js +6 -0
  55. package/dist/dist-GHTBO7CD.js.map +1 -0
  56. package/dist/enduser.d.ts +1 -0
  57. package/dist/enduser.js +7 -0
  58. package/dist/enduser.js.map +1 -0
  59. package/dist/identity.d.ts +1 -0
  60. package/dist/identity.js +6 -0
  61. package/dist/identity.js.map +1 -0
  62. package/dist/index.d.ts +601 -12
  63. package/dist/index.js +1640 -28
  64. package/dist/index.js.map +1 -0
  65. package/dist/index.node-55LOPHNQ.js +5 -0
  66. package/dist/index.node-55LOPHNQ.js.map +1 -0
  67. package/dist/lib-VRTYVDUO.js +1861 -0
  68. package/dist/lib-VRTYVDUO.js.map +1 -0
  69. package/dist/operator.d.ts +1 -0
  70. package/dist/operator.js +6 -0
  71. package/dist/operator.js.map +1 -0
  72. package/dist/paymaster.d.ts +1 -0
  73. package/dist/paymaster.js +6 -0
  74. package/dist/paymaster.js.map +1 -0
  75. package/dist/tokens.d.ts +1 -0
  76. package/dist/tokens.js +6 -0
  77. package/dist/tokens.js.map +1 -0
  78. package/dist/x402.d.ts +1 -0
  79. package/dist/x402.js +6 -0
  80. package/dist/x402.js.map +1 -0
  81. package/package.json +87 -18
  82. package/dist/clients/ExperimentClient.d.ts +0 -34
  83. package/dist/clients/ExperimentClient.js +0 -58
  84. package/dist/clients/admin.d.ts +0 -11
  85. package/dist/clients/admin.js +0 -20
  86. package/dist/clients/community.d.ts +0 -40
  87. package/dist/clients/community.js +0 -300
  88. package/dist/clients/endUser.d.ts +0 -77
  89. package/dist/clients/endUser.js +0 -298
  90. package/dist/clients/operator.d.ts +0 -66
  91. package/dist/clients/operator.js +0 -209
  92. package/dist/errors/decoder.d.ts +0 -6
  93. package/dist/errors/decoder.js +0 -44
  94. package/dist/utils/errorHandler.d.ts +0 -40
  95. package/dist/utils/errorHandler.js +0 -114
  96. package/dist/utils/funding.d.ts +0 -115
  97. package/dist/utils/funding.js +0 -188
  98. package/dist/utils/keys.d.ts +0 -61
  99. package/dist/utils/keys.js +0 -130
  100. package/dist/utils/roleData.d.ts +0 -66
  101. package/dist/utils/roleData.js +0 -128
  102. package/dist/utils/testScenarios.d.ts +0 -33
  103. package/dist/utils/testScenarios.js +0 -85
  104. package/dist/utils/userOp.d.ts +0 -89
  105. package/dist/utils/userOp.js +0 -231
@@ -1,44 +0,0 @@
1
- import { decodeErrorResult } from 'viem';
2
- import { RegistryABI } from '../index.js'; // Assuming RegistryABI is exported
3
- export const CustomErrors = {
4
- RoleNotConfigured: 'RoleNotConfigured(bytes32,bool)',
5
- RoleAlreadyGranted: 'RoleAlreadyGranted(bytes32,address)',
6
- InsufficientStake: 'InsufficientStake(uint256,uint256)',
7
- };
8
- export function decodeContractError(error) {
9
- if (!error || typeof error !== 'object')
10
- return null;
11
- // Check if it's a viem ContractFunctionExecutionError
12
- if (error.name === 'ContractFunctionExecutionError' || error.walk) {
13
- // Try to extract internal error data
14
- const internalError = error.walk ? error.walk((e) => e.data) : error;
15
- const data = internalError?.data;
16
- if (data) {
17
- try {
18
- const decoded = decodeErrorResult({
19
- abi: RegistryABI,
20
- data: data
21
- });
22
- if (decoded.errorName === 'RoleNotConfigured') {
23
- const [roleId, isActive] = decoded.args;
24
- return `RoleNotConfigured: Role ${roleId} is ${isActive ? 'ACTIVE' : 'INACTIVE'} in Registry.`;
25
- }
26
- if (decoded.errorName === 'RoleAlreadyGranted') {
27
- const [roleId, user] = decoded.args;
28
- return `RoleAlreadyGranted: User ${user} already has role ${roleId}.`;
29
- }
30
- if (decoded.errorName === 'InsufficientStake') {
31
- const [stake, minStake] = decoded.args;
32
- // Viem returns bigints, format them?
33
- return `InsufficientStake: Provided ${stake}, Required ${minStake}.`;
34
- }
35
- return `${decoded.errorName}: ${decoded.args}`;
36
- }
37
- catch (e) {
38
- // ABI mismatch or unknown error
39
- return null;
40
- }
41
- }
42
- }
43
- return null;
44
- }
@@ -1,40 +0,0 @@
1
- /**
2
- * SDK Error Handling Utilities
3
- *
4
- * 提供统一的错误处理和上下文化错误消息
5
- */
6
- import type { Hex } from 'viem';
7
- /**
8
- * 合约错误类型
9
- */
10
- export interface ContractError extends Error {
11
- data?: {
12
- errorName?: string;
13
- args?: any[];
14
- };
15
- cause?: any;
16
- shortMessage?: string;
17
- details?: string;
18
- }
19
- /**
20
- * SDK 错误上下文
21
- */
22
- export interface ErrorContext {
23
- operation: string;
24
- account?: string;
25
- contract?: string;
26
- roleId?: Hex;
27
- additionalInfo?: Record<string, any>;
28
- }
29
- /**
30
- * 处理合约错误并返回友好的错误消息
31
- *
32
- * @param error - 原始错误对象
33
- * @param context - 错误上下文
34
- * @returns 友好的错误消息
35
- */
36
- export declare function handleContractError(error: any, context: ErrorContext): Error;
37
- /**
38
- * 创建错误上下文的辅助函数
39
- */
40
- export declare function createErrorContext(operation: string, options?: Partial<ErrorContext>): ErrorContext;
@@ -1,114 +0,0 @@
1
- /**
2
- * SDK Error Handling Utilities
3
- *
4
- * 提供统一的错误处理和上下文化错误消息
5
- */
6
- /**
7
- * 已知的合约错误及其友好消息
8
- */
9
- const KNOWN_CONTRACT_ERRORS = {
10
- 'RoleAlreadyGranted': (ctx, args) => {
11
- const roleId = args?.[0] || ctx.roleId || 'unknown';
12
- const user = args?.[1] || ctx.account || 'unknown';
13
- return `Account ${user} already has this role (${roleId}). Please use a different account or exit the role first.`;
14
- },
15
- 'RoleNotConfigured': (ctx, args) => {
16
- const roleId = args?.[0] || ctx.roleId || 'unknown';
17
- return `Role ${roleId} is not configured in the Registry contract. Please configure the role first.`;
18
- },
19
- 'RoleNotGranted': (ctx, args) => {
20
- const roleId = args?.[0] || ctx.roleId || 'unknown';
21
- const user = args?.[1] || ctx.account || 'unknown';
22
- return `Account ${user} does not have role ${roleId}. Please register for this role first.`;
23
- },
24
- 'InsufficientStake': (ctx, args) => {
25
- const required = args?.[0] ? `Required: ${args[0]}` : '';
26
- const actual = args?.[1] ? `Actual: ${args[1]}` : '';
27
- return `Insufficient stake for this operation. ${required} ${actual}`.trim();
28
- },
29
- 'InsufficientBalance': (ctx, args) => {
30
- return `Insufficient balance. Please ensure you have enough tokens.`;
31
- },
32
- 'InvalidParameter': (ctx, args) => {
33
- const param = args?.[0] || 'unknown';
34
- return `Invalid parameter: ${param}. Please check your input.`;
35
- },
36
- 'Unauthorized': (ctx) => {
37
- return `Unauthorized operation. Account ${ctx.account || 'unknown'} does not have permission.`;
38
- },
39
- 'OwnableUnauthorizedAccount': (ctx, args) => {
40
- const account = args?.[0] || ctx.account || 'unknown';
41
- return `Account ${account} is not authorized to perform this operation. Only the contract owner can do this.`;
42
- }
43
- };
44
- /**
45
- * 从错误对象中提取错误名称
46
- */
47
- function extractErrorName(error) {
48
- // 检查 error.data.errorName
49
- if (error.data?.errorName) {
50
- return error.data.errorName;
51
- }
52
- // 检查 error.message 中的错误名称
53
- const message = error.message || '';
54
- const errorMatch = message.match(/Error: (\w+)\(/);
55
- if (errorMatch) {
56
- return errorMatch[1];
57
- }
58
- // 检查序列化后的错误
59
- try {
60
- const errorString = JSON.stringify(error);
61
- for (const knownError of Object.keys(KNOWN_CONTRACT_ERRORS)) {
62
- if (errorString.includes(knownError)) {
63
- return knownError;
64
- }
65
- }
66
- }
67
- catch {
68
- // Ignore serialization errors
69
- }
70
- return null;
71
- }
72
- /**
73
- * 处理合约错误并返回友好的错误消息
74
- *
75
- * @param error - 原始错误对象
76
- * @param context - 错误上下文
77
- * @returns 友好的错误消息
78
- */
79
- export function handleContractError(error, context) {
80
- const contractError = error;
81
- // 提取错误名称
82
- const errorName = extractErrorName(contractError);
83
- // 如果是已知错误,返回友好消息
84
- if (errorName && KNOWN_CONTRACT_ERRORS[errorName]) {
85
- const args = contractError.data?.args;
86
- const friendlyMessage = KNOWN_CONTRACT_ERRORS[errorName](context, args);
87
- // 创建新错误,保留原始错误作为 cause
88
- const enhancedError = new Error(`Failed to ${context.operation}: ${friendlyMessage}`);
89
- enhancedError.cause = error;
90
- enhancedError.originalError = error;
91
- enhancedError.errorName = errorName;
92
- enhancedError.context = context;
93
- return enhancedError;
94
- }
95
- // 未知错误,返回带上下文的原始错误消息
96
- const originalMessage = contractError.message ||
97
- contractError.shortMessage ||
98
- contractError.details ||
99
- 'Unknown error';
100
- const enhancedError = new Error(`Failed to ${context.operation}: ${originalMessage}`);
101
- enhancedError.cause = error;
102
- enhancedError.originalError = error;
103
- enhancedError.context = context;
104
- return enhancedError;
105
- }
106
- /**
107
- * 创建错误上下文的辅助函数
108
- */
109
- export function createErrorContext(operation, options) {
110
- return {
111
- operation,
112
- ...options
113
- };
114
- }
@@ -1,115 +0,0 @@
1
- import { type Hex, type Address, type Chain } from 'viem';
2
- /**
3
- * 资金管理参数
4
- */
5
- export interface FundingParams {
6
- /** RPC URL */
7
- rpcUrl: string;
8
- /** 链配置 */
9
- chain: Chain;
10
- /** 资金提供者私钥 */
11
- supplierKey: Hex;
12
- /** 目标地址 */
13
- targetAddress: Address;
14
- }
15
- /**
16
- * ETH 充值参数
17
- */
18
- export interface FundETHParams extends FundingParams {
19
- /** 充值金额(ETH,如 '0.1') */
20
- amount: string;
21
- }
22
- /**
23
- * ERC20 充值参数
24
- */
25
- export interface FundTokenParams extends FundingParams {
26
- /** Token 合约地址 */
27
- tokenAddress: Address;
28
- /** 充值金额(Token,如 '100') */
29
- amount: string;
30
- }
31
- /**
32
- * 智能充值参数
33
- */
34
- export interface EnsureFundingParams extends FundingParams {
35
- /** 最小 ETH 余额阈值 */
36
- minETH?: string;
37
- /** 目标 ETH 充值金额 */
38
- targetETH?: string;
39
- /** Token 配置(可选) */
40
- token?: {
41
- address: Address;
42
- minBalance?: string;
43
- targetAmount?: string;
44
- };
45
- }
46
- /**
47
- * 充值结果
48
- */
49
- export interface FundingResult {
50
- success: boolean;
51
- txHash?: Hex;
52
- error?: string;
53
- }
54
- /**
55
- * 资金管理器
56
- * 提供 ETH 和 ERC20 Token 的充值、验证等工具函数
57
- */
58
- export declare class FundingManager {
59
- /**
60
- * 创建 PublicClient 和 WalletClient
61
- */
62
- private static createClients;
63
- /**
64
- * 充值 ETH 到目标地址
65
- * @param params - 充值参数
66
- * @returns 充值结果
67
- */
68
- static fundWithETH(params: FundETHParams): Promise<FundingResult>;
69
- /**
70
- * 充值 ERC20 Token 到目标地址
71
- * @param params - 充值参数
72
- * @returns 充值结果
73
- */
74
- static fundWithToken(params: FundTokenParams): Promise<FundingResult>;
75
- /**
76
- * 检查 ETH 余额
77
- * @param params - 基础参数
78
- * @returns ETH 余额(wei)
79
- */
80
- static getETHBalance(params: FundingParams): Promise<bigint>;
81
- /**
82
- * 检查 ERC20 Token 余额
83
- * @param params - 基础参数
84
- * @param tokenAddress - Token 合约地址
85
- * @returns Token 余额
86
- */
87
- static getTokenBalance(params: FundingParams, tokenAddress: Address): Promise<bigint>;
88
- /**
89
- * 智能充值:检查余额,不足时自动充值
90
- * @param params - 充值参数
91
- * @returns 充值结果数组
92
- */
93
- static ensureFunding(params: EnsureFundingParams): Promise<FundingResult[]>;
94
- /**
95
- * 批量充值 ETH
96
- * @param params - 基础参数
97
- * @param targets - 目标地址和金额数组
98
- * @returns 充值结果数组
99
- */
100
- static batchFundETH(params: Omit<FundingParams, 'targetAddress'>, targets: Array<{
101
- address: Address;
102
- amount: string;
103
- }>): Promise<FundingResult[]>;
104
- /**
105
- * 批量充值 Token
106
- * @param params - 基础参数
107
- * @param tokenAddress - Token 合约地址
108
- * @param targets - 目标地址和金额数组
109
- * @returns 充值结果数组
110
- */
111
- static batchFundToken(params: Omit<FundingParams, 'targetAddress'>, tokenAddress: Address, targets: Array<{
112
- address: Address;
113
- amount: string;
114
- }>): Promise<FundingResult[]>;
115
- }
@@ -1,188 +0,0 @@
1
- import { createPublicClient, createWalletClient, http, parseEther, erc20Abi } from 'viem';
2
- import { privateKeyToAccount } from 'viem/accounts';
3
- /**
4
- * 资金管理器
5
- * 提供 ETH 和 ERC20 Token 的充值、验证等工具函数
6
- */
7
- export class FundingManager {
8
- /**
9
- * 创建 PublicClient 和 WalletClient
10
- */
11
- static createClients(params) {
12
- const account = privateKeyToAccount(params.supplierKey);
13
- const transport = http(params.rpcUrl);
14
- const publicClient = createPublicClient({
15
- chain: params.chain,
16
- transport
17
- });
18
- const walletClient = createWalletClient({
19
- account,
20
- chain: params.chain,
21
- transport
22
- });
23
- return { publicClient, walletClient, account };
24
- }
25
- /**
26
- * 充值 ETH 到目标地址
27
- * @param params - 充值参数
28
- * @returns 充值结果
29
- */
30
- static async fundWithETH(params) {
31
- try {
32
- const { publicClient, walletClient } = this.createClients(params);
33
- const amount = parseEther(params.amount);
34
- console.log(`💸 Funding ${params.targetAddress} with ${params.amount} ETH...`);
35
- const hash = await walletClient.sendTransaction({
36
- account: walletClient.account,
37
- chain: params.chain,
38
- to: params.targetAddress,
39
- value: amount
40
- });
41
- console.log(` Transaction Sent: ${hash}`);
42
- await publicClient.waitForTransactionReceipt({ hash });
43
- console.log(` ✅ ETH Funded.`);
44
- return { success: true, txHash: hash };
45
- }
46
- catch (error) {
47
- console.error(` ❌ ETH Funding Failed:`, error);
48
- return { success: false, error: error.message };
49
- }
50
- }
51
- /**
52
- * 充值 ERC20 Token 到目标地址
53
- * @param params - 充值参数
54
- * @returns 充值结果
55
- */
56
- static async fundWithToken(params) {
57
- try {
58
- const { publicClient, walletClient, account } = this.createClients(params);
59
- const amount = parseEther(params.amount);
60
- console.log(`💸 Funding ${params.targetAddress} with ${params.amount} tokens...`);
61
- const { request } = await publicClient.simulateContract({
62
- account,
63
- address: params.tokenAddress,
64
- abi: erc20Abi,
65
- functionName: 'transfer',
66
- args: [params.targetAddress, amount]
67
- });
68
- const hash = await walletClient.writeContract(request);
69
- console.log(` Transaction Sent: ${hash}`);
70
- await publicClient.waitForTransactionReceipt({ hash });
71
- console.log(` ✅ Token Funded.`);
72
- return { success: true, txHash: hash };
73
- }
74
- catch (error) {
75
- console.error(` ❌ Token Funding Failed:`, error);
76
- return { success: false, error: error.message };
77
- }
78
- }
79
- /**
80
- * 检查 ETH 余额
81
- * @param params - 基础参数
82
- * @returns ETH 余额(wei)
83
- */
84
- static async getETHBalance(params) {
85
- const { publicClient } = this.createClients(params);
86
- return await publicClient.getBalance({ address: params.targetAddress });
87
- }
88
- /**
89
- * 检查 ERC20 Token 余额
90
- * @param params - 基础参数
91
- * @param tokenAddress - Token 合约地址
92
- * @returns Token 余额
93
- */
94
- static async getTokenBalance(params, tokenAddress) {
95
- const { publicClient } = this.createClients(params);
96
- return await publicClient.readContract({
97
- address: tokenAddress,
98
- abi: erc20Abi,
99
- functionName: 'balanceOf',
100
- args: [params.targetAddress]
101
- });
102
- }
103
- /**
104
- * 智能充值:检查余额,不足时自动充值
105
- * @param params - 充值参数
106
- * @returns 充值结果数组
107
- */
108
- static async ensureFunding(params) {
109
- const results = [];
110
- const { publicClient } = this.createClients(params);
111
- // 1. 检查并充值 ETH
112
- if (params.minETH && params.targetETH) {
113
- const ethBalance = await publicClient.getBalance({ address: params.targetAddress });
114
- const minETH = parseEther(params.minETH);
115
- const targetETH = parseEther(params.targetETH);
116
- if (ethBalance < minETH) {
117
- console.log(`⚠️ ETH balance (${Number(ethBalance) / 1e18}) below threshold (${params.minETH})`);
118
- const result = await this.fundWithETH({
119
- ...params,
120
- amount: params.targetETH
121
- });
122
- results.push(result);
123
- }
124
- else {
125
- console.log(`✅ Sufficient ETH: ${Number(ethBalance) / 1e18} ETH`);
126
- results.push({ success: true });
127
- }
128
- }
129
- // 2. 检查并充值 Token
130
- if (params.token) {
131
- const tokenBalance = await this.getTokenBalance(params, params.token.address);
132
- const minToken = params.token.minBalance ? parseEther(params.token.minBalance) : 0n;
133
- const targetToken = params.token.targetAmount ? parseEther(params.token.targetAmount) : 0n;
134
- if (tokenBalance < minToken && targetToken > 0n) {
135
- console.log(`⚠️ Token balance (${Number(tokenBalance) / 1e18}) below threshold (${params.token.minBalance})`);
136
- const result = await this.fundWithToken({
137
- ...params,
138
- tokenAddress: params.token.address,
139
- amount: params.token.targetAmount
140
- });
141
- results.push(result);
142
- }
143
- else {
144
- console.log(`✅ Sufficient Token: ${Number(tokenBalance) / 1e18}`);
145
- results.push({ success: true });
146
- }
147
- }
148
- return results;
149
- }
150
- /**
151
- * 批量充值 ETH
152
- * @param params - 基础参数
153
- * @param targets - 目标地址和金额数组
154
- * @returns 充值结果数组
155
- */
156
- static async batchFundETH(params, targets) {
157
- const results = [];
158
- for (const target of targets) {
159
- const result = await this.fundWithETH({
160
- ...params,
161
- targetAddress: target.address,
162
- amount: target.amount
163
- });
164
- results.push(result);
165
- }
166
- return results;
167
- }
168
- /**
169
- * 批量充值 Token
170
- * @param params - 基础参数
171
- * @param tokenAddress - Token 合约地址
172
- * @param targets - 目标地址和金额数组
173
- * @returns 充值结果数组
174
- */
175
- static async batchFundToken(params, tokenAddress, targets) {
176
- const results = [];
177
- for (const target of targets) {
178
- const result = await this.fundWithToken({
179
- ...params,
180
- targetAddress: target.address,
181
- tokenAddress,
182
- amount: target.amount
183
- });
184
- results.push(result);
185
- }
186
- return results;
187
- }
188
- }
@@ -1,61 +0,0 @@
1
- import type { Hex, Address } from 'viem';
2
- /**
3
- * 密钥对接口
4
- */
5
- export interface KeyPair {
6
- name: string;
7
- privateKey: Hex;
8
- address: Address;
9
- }
10
- /**
11
- * 密钥管理器
12
- * 提供密钥生成、存储、加载等工具函数
13
- */
14
- export declare class KeyManager {
15
- /**
16
- * 生成单个密钥对
17
- * @param name - 密钥名称(如 'Jason', 'Anni')
18
- */
19
- static generateKeyPair(name: string): KeyPair;
20
- /**
21
- * 批量生成密钥对
22
- * @param names - 密钥名称数组
23
- */
24
- static generateKeyPairs(names: string[]): KeyPair[];
25
- /**
26
- * 生成指定数量的密钥对(自动命名为 Operator_1, Operator_2, ...)
27
- * @param count - 数量
28
- * @param prefix - 名称前缀(默认 'Operator')
29
- */
30
- static generateMultiple(count: number, prefix?: string): KeyPair[];
31
- /**
32
- * 保存密钥到 .env 文件
33
- * @param filePath - 文件路径(绝对路径)
34
- * @param keys - 密钥对数组
35
- * @param overwrite - 是否覆盖已存在的文件(默认 false)
36
- */
37
- static saveToEnvFile(filePath: string, keys: KeyPair[], overwrite?: boolean): void;
38
- /**
39
- * 从 .env 文件加载密钥
40
- * @param filePath - 文件路径(绝对路径)
41
- * @returns 密钥对数组
42
- */
43
- static loadFromEnvFile(filePath: string): KeyPair[];
44
- /**
45
- * 保存密钥到 JSON 文件(包含地址信息)
46
- * @param filePath - 文件路径(绝对路径)
47
- * @param keys - 密钥对数组
48
- * @param overwrite - 是否覆盖已存在的文件(默认 false)
49
- */
50
- static saveToJsonFile(filePath: string, keys: KeyPair[], overwrite?: boolean): void;
51
- /**
52
- * 从 JSON 文件加载密钥
53
- * @param filePath - 文件路径(绝对路径)
54
- */
55
- static loadFromJsonFile(filePath: string): KeyPair[];
56
- /**
57
- * 打印密钥信息(隐藏私钥)
58
- * @param keys - 密钥对数组
59
- */
60
- static printKeys(keys: KeyPair[], showPrivateKey?: boolean): void;
61
- }
@@ -1,130 +0,0 @@
1
- import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
2
- import * as fs from 'fs';
3
- /**
4
- * 密钥管理器
5
- * 提供密钥生成、存储、加载等工具函数
6
- */
7
- export class KeyManager {
8
- /**
9
- * 生成单个密钥对
10
- * @param name - 密钥名称(如 'Jason', 'Anni')
11
- */
12
- static generateKeyPair(name) {
13
- const privateKey = generatePrivateKey();
14
- const account = privateKeyToAccount(privateKey);
15
- return {
16
- name,
17
- privateKey,
18
- address: account.address
19
- };
20
- }
21
- /**
22
- * 批量生成密钥对
23
- * @param names - 密钥名称数组
24
- */
25
- static generateKeyPairs(names) {
26
- return names.map(name => this.generateKeyPair(name));
27
- }
28
- /**
29
- * 生成指定数量的密钥对(自动命名为 Operator_1, Operator_2, ...)
30
- * @param count - 数量
31
- * @param prefix - 名称前缀(默认 'Operator')
32
- */
33
- static generateMultiple(count, prefix = 'Operator') {
34
- const names = Array.from({ length: count }, (_, i) => `${prefix}_${i + 1}`);
35
- return this.generateKeyPairs(names);
36
- }
37
- /**
38
- * 保存密钥到 .env 文件
39
- * @param filePath - 文件路径(绝对路径)
40
- * @param keys - 密钥对数组
41
- * @param overwrite - 是否覆盖已存在的文件(默认 false)
42
- */
43
- static saveToEnvFile(filePath, keys, overwrite = false) {
44
- if (fs.existsSync(filePath) && !overwrite) {
45
- throw new Error(`File already exists: ${filePath}. Set overwrite=true to replace.`);
46
- }
47
- const content = keys.map(k => `${k.name.toUpperCase().replace(/\s+/g, '_')}_PRIVATE_KEY=${k.privateKey}`).join('\n') + '\n';
48
- fs.writeFileSync(filePath, content, { mode: 0o600 }); // 仅所有者可读写
49
- console.log(`✅ Keys saved to ${filePath} (${keys.length} keys)`);
50
- }
51
- /**
52
- * 从 .env 文件加载密钥
53
- * @param filePath - 文件路径(绝对路径)
54
- * @returns 密钥对数组
55
- */
56
- static loadFromEnvFile(filePath) {
57
- if (!fs.existsSync(filePath)) {
58
- throw new Error(`File not found: ${filePath}`);
59
- }
60
- const content = fs.readFileSync(filePath, 'utf-8');
61
- const lines = content.split('\n').filter(line => line.trim() && !line.startsWith('#'));
62
- return lines.map(line => {
63
- const [key, value] = line.split('=');
64
- const name = key.replace(/_PRIVATE_KEY$/, '').toLowerCase().replace(/_/g, ' ');
65
- const privateKey = value.trim();
66
- const account = privateKeyToAccount(privateKey);
67
- return {
68
- name,
69
- privateKey,
70
- address: account.address
71
- };
72
- });
73
- }
74
- /**
75
- * 保存密钥到 JSON 文件(包含地址信息)
76
- * @param filePath - 文件路径(绝对路径)
77
- * @param keys - 密钥对数组
78
- * @param overwrite - 是否覆盖已存在的文件(默认 false)
79
- */
80
- static saveToJsonFile(filePath, keys, overwrite = false) {
81
- if (fs.existsSync(filePath) && !overwrite) {
82
- throw new Error(`File already exists: ${filePath}. Set overwrite=true to replace.`);
83
- }
84
- const data = {
85
- generated: new Date().toISOString(),
86
- keys: keys.map(k => ({
87
- name: k.name,
88
- privateKey: k.privateKey,
89
- address: k.address
90
- }))
91
- };
92
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { mode: 0o600 });
93
- console.log(`✅ Keys saved to ${filePath} (${keys.length} keys)`);
94
- }
95
- /**
96
- * 从 JSON 文件加载密钥
97
- * @param filePath - 文件路径(绝对路径)
98
- */
99
- static loadFromJsonFile(filePath) {
100
- if (!fs.existsSync(filePath)) {
101
- throw new Error(`File not found: ${filePath}`);
102
- }
103
- const content = fs.readFileSync(filePath, 'utf-8');
104
- const data = JSON.parse(content);
105
- return data.keys.map((k) => ({
106
- name: k.name,
107
- privateKey: k.privateKey,
108
- address: k.address
109
- }));
110
- }
111
- /**
112
- * 打印密钥信息(隐藏私钥)
113
- * @param keys - 密钥对数组
114
- */
115
- static printKeys(keys, showPrivateKey = false) {
116
- console.log('\n🔑 Generated Keys:');
117
- console.log('─'.repeat(80));
118
- keys.forEach((k, i) => {
119
- console.log(`${i + 1}. ${k.name}`);
120
- console.log(` Address: ${k.address}`);
121
- if (showPrivateKey) {
122
- console.log(` Private Key: ${k.privateKey}`);
123
- }
124
- else {
125
- console.log(` Private Key: ${k.privateKey.slice(0, 10)}...${k.privateKey.slice(-8)}`);
126
- }
127
- });
128
- console.log('─'.repeat(80));
129
- }
130
- }