-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
169 lines (143 loc) Β· 5.41 KB
/
index.js
File metadata and controls
169 lines (143 loc) Β· 5.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
require('dotenv').config();
const {
alchemy,
createAlchemySmartAccountClient,
sepolia,
getAlchemyPaymasterAddress,
} = require('@account-kit/infra');
const { createLightAccount } = require('@account-kit/smart-contracts');
const { LocalAccountSigner } = require('@aa-sdk/core');
const { encodeFunctionData, parseAbi } = require('viem');
const { privateKeyToAccount } = require('viem/accounts');
async function main() {
try {
console.log('π Starting AA Wallet and ERC-20 Sponsored Transaction Demo\n');
// Check required environment variables
const requiredEnvVars = ['ALCHEMY_API_KEY', 'GAS_MANAGER_POLICY_ID'];
for (const envVar of requiredEnvVars) {
if (!process.env[envVar]) {
throw new Error(`Missing required environment variable: ${envVar}`);
}
}
const {
ALCHEMY_API_KEY,
GAS_MANAGER_POLICY_ID,
ERC20_RULE_POLICY_ID,
TOKEN_ADDRESS = '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // USDC on Sepolia
MAX_TOKEN_AMOUNT = '10000000', // 10 USDC
TARGET_ADDRESS = '0x9C179d698ddb0f9BEE55d223AE7D354597a8F877',
} = process.env;
// Generate or use existing private key
const privateKey = process.env.PRIVATE_KEY || '0x' + require('crypto').randomBytes(32).toString('hex');
console.log('π Using private key:', privateKey);
// 1. Create Alchemy transport
console.log('π Creating Alchemy transport...');
const alchemyTransport = alchemy({
apiKey: ALCHEMY_API_KEY,
});
// 2. Create Light Account (AA Wallet)
const signer = LocalAccountSigner.privateKeyToAccountSigner(privateKey);
console.log('πΌ Creating AA wallet...');
const account = await createLightAccount({
chain: sepolia,
transport: alchemyTransport,
signer: LocalAccountSigner.privateKeyToAccountSigner(privateKey),
});
console.log('β
AA Wallet created successfully!');
console.log('π Wallet address:', account.address);
const ifErc20 = false;
let policy = {
transport: alchemyTransport,
policyId: GAS_MANAGER_POLICY_ID,
chain: sepolia,
account: account,
}
// 3. Create Smart Account Client with ERC-20 sponsorship policy
console.log('π§ Creating smart account client...');
if (ifErc20) {
policy.policyId = ERC20_RULE_POLICY_ID;
policy.policyToken = {
address: TOKEN_ADDRESS,
maxTokenAmount: BigInt(MAX_TOKEN_AMOUNT),
}
}
const client = createAlchemySmartAccountClient({
...policy,
});
console.log('β
Smart account client created with ERC-20 policy!');
// 4. Prepare ERC-20 approval and USDC transfer
console.log('π Preparing to send 0.01 USDC to', TARGET_ADDRESS);
const erc20Abi = parseAbi([
'function approve(address spender, uint256 amount) public returns (bool)',
'function transfer(address to, uint256 amount) public returns (bool)',
]);
const paymasterAddress = getAlchemyPaymasterAddress(sepolia, '0.7.0');
console.log('π° Paymaster address:', paymasterAddress);
// 5. Send sponsored UserOperation with ERC-20 payment
console.log('π Sending sponsored transaction...');
const userOpResult = await client.sendUserOperation({
uo: [
{
// First: approve the paymaster to spend ERC-20 tokens
target: TOKEN_ADDRESS,
data: encodeFunctionData({
abi: erc20Abi,
functionName: 'approve',
args: [paymasterAddress, BigInt(MAX_TOKEN_AMOUNT)],
}),
},
{
// Second: send 0.01 USDC to target address
target: TOKEN_ADDRESS,
data: encodeFunctionData({
abi: erc20Abi,
functionName: 'transfer',
args: [TARGET_ADDRESS, 10000n], // 0.01 USDC = 10000 (6 decimals)
}),
value: 0n, // No ETH value
},
],
});
console.log('β
Transaction sent successfully!');
console.log('π UserOperation hash:', userOpResult.hash);
// 6. Wait for transaction receipt
console.log('β³ Waiting for transaction receipt...');
const receipt = await client.waitForUserOperationTransaction({
hash: userOpResult.hash,
});
console.log('β
Transaction confirmed!');
console.log('π§Ύ Transaction hash:', receipt.transactionHash);
console.log('β½ Gas used:', receipt.gasUsed?.toString());
console.log('π¦ Block number:', receipt.blockNumber?.toString());
console.log('\nπ Demo completed successfully!');
console.log('π‘ Summary:');
console.log(' - Created AA wallet:', account.address);
console.log(' - Sent 0.01 USDC to:', TARGET_ADDRESS);
console.log(' - Used ERC-20 token for gas payment:', TOKEN_ADDRESS);
console.log(' - Transaction hash:', receipt.transactionHash);
} catch (error) {
console.error('β Error:', error.message);
process.exit(1);
}
}
// Add some helper functions for debugging
async function checkBalance(client, tokenAddress) {
try {
const balanceAbi = parseAbi(['function balanceOf(address) view returns (uint256)']);
const balance = await client.readContract({
address: tokenAddress,
abi: balanceAbi,
functionName: 'balanceOf',
args: [client.account.address],
});
return balance;
} catch (error) {
console.warn('Could not fetch balance:', error.message);
return null;
}
}
// Run the main function
if (require.main === module) {
main();
}
module.exports = { main };