-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
233 lines (195 loc) · 6.28 KB
/
index.ts
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import { createSmartAccountClient } from "permissionless"
import { Address, Hex, createPublicClient, encodeFunctionData, getContract, http, parseAbi, parseEther, recoverMessageAddress, toHex } from "viem"
import { sepolia } from "viem/chains"
import { privateKeyToAccount } from "viem/accounts"
import { entryPoint07Address } from "viem/account-abstraction";
import { createPimlicoClient } from "permissionless/clients/pimlico"
import { toSimpleSmartAccount } from "permissionless/accounts";
import { MagicSpendStakeManagerAbi } from "./abi/MagicSpendStakeManager";
import { MagicSpendWithdrawalManagerAbi } from "./abi/MagicSpendWithdrawalManager";
import "dotenv/config"
import { MagicSpendAllowance, MagicSpendWithdrawal } from "./types";
const RPC_URL = "https://11155111.rpc.thirdweb.com"
const ETH: Address = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"
const amount = 123; // 123 wei
const PRIVATE_KEY = process.env.ACCOUNT_PRIVATE_KEY;
if (PRIVATE_KEY === undefined) {
throw new Error("ACCOUNT_PRIVATE_KEY env var is required")
}
const PIMLICO_URL = process.env.PIMLICO_URL;
if (PIMLICO_URL === undefined) {
throw new Error("PIMLICO_URL env var is required")
}
export const publicClient = createPublicClient({
transport: http(RPC_URL),
chain: sepolia,
})
const pimlicoClient = createPimlicoClient({
transport: http(PIMLICO_URL),
chain: sepolia,
entryPoint: {
address: entryPoint07Address,
version: "0.7",
},
})
const sendMagicSpendRequest = async (method: string, params: any[]) => {
const body = {
jsonrpc: "2.0",
method,
params,
id: 1,
};
console.log('=== magic spend request ===');
console.log(JSON.stringify(body, null, 4));
const response = await fetch(PIMLICO_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
const j = await response.json();
console.log('=== magic spend response ===');
console.log(JSON.stringify(j, null, 4));
console.log('============================');
// @ts-ignore
return j.result;
}
const main = async () => {
const signer = privateKeyToAccount(PRIVATE_KEY as Hex)
console.log(`Signer address: ${signer.address}`)
const simpleAccount = await toSimpleSmartAccount({
client: publicClient,
owner: signer,
entryPoint: {
address: entryPoint07Address,
version: "0.7",
},
});
const smartAccountClient = createSmartAccountClient({
account: simpleAccount,
chain: sepolia,
bundlerTransport: http(PIMLICO_URL, {
timeout: 60_000,
}),
userOperation: {
estimateFeesPerGas: async () => {
return (await pimlicoClient.getUserOperationGasPrice()).fast
},
},
paymaster: pimlicoClient,
})
// Check at least one stake exists
const {
stakeManagerAddress,
withdrawalManagerAddress,
} = await sendMagicSpendRequest(
'pimlico_getMagicSpendContracts',
[]
)
const stakeManagerContract = getContract({
abi: MagicSpendStakeManagerAbi,
address: stakeManagerAddress,
client: publicClient,
})
const stakes = await sendMagicSpendRequest(
'pimlico_getMagicSpendStakes',
[{
account: signer.address,
asset: ETH
}]
)
if (stakes.length === 0) {
throw new Error("No stakes found")
}
const allowance = (await sendMagicSpendRequest(
'pimlico_prepareMagicSpendAllowance',
[{
account: signer.address,
token: ETH,
amount: toHex(amount),
}]
)) as MagicSpendAllowance;
const hash_ = await stakeManagerContract.read.getAllowanceHash([
{
...allowance,
validAfter: Number(allowance.validAfter),
validUntil: Number(allowance.validUntil),
salt: Number(allowance.salt),
}
]) as Hex;
const allowanceSignature = await signer.signMessage({
message: {
raw: hash_,
}
})
await sendMagicSpendRequest(
"pimlico_grantMagicSpendAllowance",
[{
allowance,
signature: allowanceSignature
}]
);
const withdrawalManagerContract = getContract({
abi: MagicSpendWithdrawalManagerAbi,
address: withdrawalManagerAddress,
client: publicClient,
})
const operatorRequestHash = await withdrawalManagerContract.read.getWithdrawalHash([
{
token: ETH,
amount: BigInt(amount),
chainId: BigInt(sepolia.id),
recipient: simpleAccount.address,
preCalls: [],
postCalls: [],
validUntil: Number(0),
validAfter: Number(0),
salt: 0
}
]) as Hex;
const operatorRequestSignature = await signer.signMessage({
message: {
raw: operatorRequestHash
}
})
const [wiithdrawal, withdrawalSignature] = await sendMagicSpendRequest(
"pimlico_sponsorMagicSpendWithdrawal",
[{
recipient: simpleAccount.address,
token: ETH,
amount,
salt: 0,
signature: operatorRequestSignature
}]
)
const magicSpendCallData = encodeFunctionData({
abi: MagicSpendWithdrawalManagerAbi,
functionName: 'withdraw',
args: [
wiithdrawal,
withdrawalSignature,
]
})
// Send user operation and withdraw funds
// You can add subsequent calls after the withdrawal, like "buy NFT on OpenSea for ETH"
const userOpHash = await smartAccountClient.sendUserOperation({
account: simpleAccount,
calls: [
{
to: withdrawalManagerAddress,
value: parseEther("0"),
data: magicSpendCallData,
}
]
})
console.log(`Userop hash: ${userOpHash}`);
const receipt = await pimlicoClient.waitForUserOperationReceipt({
hash: userOpHash
})
console.log(`Transaction hash: ${receipt.receipt.transactionHash}`);
}
main()
.then(console.log)
.catch(console.error)
.finally(() => process.exit(0))