-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathdapp.test.ts
More file actions
543 lines (428 loc) · 20.9 KB
/
dapp.test.ts
File metadata and controls
543 lines (428 loc) · 20.9 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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import { commons, v2 } from '@0xsequence/core'
import { SequenceClient, SequenceProvider, DefaultProviderConfig, MemoryItemStore } from '@0xsequence/provider'
import { context } from '@0xsequence/tests'
import { configureLogger } from '@0xsequence/utils'
import { ethers, TypedDataDomain, TypedDataField } from 'ethers'
import { test, assert } from '../../utils/assert'
import { testAccounts, getEOAWallet, sendETH } from '../testutils'
configureLogger({ logLevel: 'DEBUG', silence: false })
export const tests = async () => {
//
// Setup
//
const transportsConfig = {
...DefaultProviderConfig.transports,
walletAppURL: 'http://localhost:9999/mock-wallet/mock-wallet.test.html'
}
//
// Deploy Sequence WalletContext (deterministic).
//
const deployedWalletContext = await (async () => {
const provider = new ethers.providers.JsonRpcProvider('http://localhost:8545')
const signer = provider.getSigner()
return context.deploySequenceContexts(signer)
})()
const hardhatProvider = new ethers.providers.JsonRpcProvider('http://localhost:8545')
const client = new SequenceClient(transportsConfig, new MemoryItemStore(), { defaultChainId: 31337 })
const wallet = new SequenceProvider(client, chainId => {
if (chainId === 31337) {
return hardhatProvider
}
if (chainId === 31338) {
return new ethers.providers.JsonRpcProvider('http://localhost:9545')
}
throw new Error(`No provider for chainId ${chainId}`)
})
// provider + signer, by default if a chainId is not specified it will direct
// requests to the defaultChain
const provider = wallet.getProvider()
const signer = wallet.getSigner()
// clear it in case we're testing in browser session
await wallet.disconnect()
await test('is disconnected / logged out', async () => {
assert.false(wallet.isConnected(), 'is connected')
})
await test('is closed', async () => {
assert.false(wallet.isOpened(), 'is closed')
})
await test('is disconnected', async () => {
assert.false(wallet.isConnected(), 'is disconnnected')
})
await test('connect', async () => {
const { connected } = await wallet.connect({
app: 'test',
keepWalletOpened: true
})
assert.true(connected, 'is connected')
})
await test('isOpened', async () => {
assert.true(wallet.isOpened(), 'is opened')
})
await test('isConnected', async () => {
assert.true(wallet.isConnected(), 'is connected')
})
let walletContext: commons.context.VersionedContext
await test('getWalletContext', async () => {
walletContext = await wallet.getWalletContext()
assert.equal(walletContext[1].factory, deployedWalletContext[1].factory, 'wallet context factory')
assert.equal(walletContext[1].guestModule, deployedWalletContext[1].guestModule, 'wallet context guestModule')
assert.equal(walletContext[2].factory, deployedWalletContext[2].factory, 'wallet context factory')
assert.equal(walletContext[2].guestModule, deployedWalletContext[2].guestModule, 'wallet context guestModule')
})
await test('getChainId', async () => {
const chainId = wallet.getChainId()
assert.equal(chainId, 31337, 'chainId is correct')
})
await test('networks', async () => {
const networks = await wallet.getNetworks()
assert.equal(networks.length, 2, '2 networks')
assert.true(networks[0].isDefaultChain!, '1st network is DefaultChain')
assert.true(!networks[1].isDefaultChain, '1st network is not DefaultChain')
assert.equal(networks[1].chainId, 31338, 'authChainId is correct')
const authProvider = wallet.getProvider(31338)!
assert.equal(authProvider.getChainId(), 31338, 'authProvider chainId is 31338')
assert.equal(provider.getChainId(), 31337, 'provider chainId is 31337')
})
await test('getAddress', async () => {
const address = wallet.getAddress()
assert.true(ethers.utils.isAddress(address), 'wallet address is valid')
})
await test('getWalletConfig', async () => {
const allWalletConfigs = await wallet.getWalletConfig()
const config = allWalletConfigs as v2.config.WalletConfig
assert.equal(config.version, 2, 'wallet config version is correct')
assert.true(ethers.BigNumber.from(2).eq(config.threshold), 'config, 2 threshold')
assert.true(ethers.BigNumber.from(0).eq(config.checkpoint), 'config, 0 checkpoint')
assert.true(v2.config.isSignerLeaf(config.tree), 'config, isSignerLeaf')
assert.true(ethers.utils.isAddress((config.tree as v2.config.SignerLeaf).address), 'config, signer address')
assert.true(ethers.BigNumber.from(2).eq((config.tree as v2.config.SignerLeaf).weight), 'config, signer weight')
})
await test('multiple networks', async () => {
// chainId 31337
{
assert.equal(provider.getChainId(), 31337, 'provider chainId is 31337')
const network = await provider.getNetwork()
assert.equal(network.chainId, 31337, 'chain id match')
const netVersion = await provider.send('net_version', [])
assert.equal(netVersion, '31337', 'net_version check')
const chainId = await provider.send('eth_chainId', [])
assert.equal(chainId, ethers.utils.hexValue(31337), 'eth_chainId check')
const chainId2 = await signer.getChainId()
assert.equal(chainId2, 31337, 'chainId check')
}
// chainId 31338
{
const provider2 = wallet.getProvider(31338)
assert.equal(provider2.getChainId(), 31338, '2nd chain, chainId is 31338 - 2')
const network = await provider2.getNetwork()
assert.equal(network.chainId, 31338, '2nd chain, chain id match - 3')
const netVersion = await provider2.send('net_version', [])
assert.equal(netVersion, '31338', '2nd chain, net_version check - 4')
const chainId = await provider2.send('eth_chainId', [])
assert.equal(chainId, ethers.utils.hexValue(31338), '2nd chain, eth_chainId check - 5')
const chainId2 = await provider2.getSigner().getChainId()
assert.equal(chainId2, 31338, '2nd chain, chainId check - 6')
}
})
await test('listAccounts', async () => {
const signers = provider.listAccounts()
assert.true(signers.length === 1, 'signers, single owner')
assert.true(signers[0] === wallet.getAddress(), 'signers, check address')
})
await test('signMessage on defaultChain', async () => {
const address = wallet.getAddress()
const chainId = wallet.getChainId()
const message = 'hihi'
const message2 = ethers.utils.toUtf8Bytes('hihi')
// Sign the message
const sigs = await Promise.all(
[message, message2].map(async m => {
assert.equal(await signer.getChainId(), 31337, 'signer chainId is 31337')
// NOTE: below line is equivalent to `signer.signMessage(m)` call
// const sig = await wallet.utils.signMessage(m)
const sig = await signer.signMessage(m, { eip6492: true })
// Non-deployed wallet (with EIP6492) should return a signature
// that ends with the EIP-6492 magic bytes
const suffix = '6492649264926492649264926492649264926492649264926492649264926492'
assert.true(sig.endsWith(suffix), 'signature ends with EIP-6492 magic bytes')
return sig
})
)
const sig = sigs[0]
// Verify the signature
const isValid = await wallet.utils.isValidMessageSignature(address, message, sig, chainId)
assert.true(isValid, 'signature is valid - 2')
})
await test('signTypedData on defaultChain', async () => {
const address = wallet.getAddress()
const chainId = wallet.getChainId()
const domain: TypedDataDomain = {
name: 'Ether Mail',
version: '1',
chainId: chainId,
verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC'
}
const types: { [key: string]: TypedDataField[] } = {
Person: [
{ name: 'name', type: 'string' },
{ name: 'wallet', type: 'address' }
]
}
const message = {
name: 'Bob',
wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB'
}
const sig = await signer.signTypedData(domain, types, message)
// Verify typed data
const isValid = await wallet.utils.isValidTypedDataSignature(address, { domain, types, message }, sig, chainId)
assert.true(isValid, 'signature is valid - 3')
})
await test('signAuthMessage', async () => {
const address = wallet.getAddress()
const chainId = 31337
const authProvider = wallet.getProvider(chainId)!
assert.equal(chainId, 31337, 'chainId is 31337 (authChain)')
assert.equal(authProvider.getChainId(), 31337, 'authProvider chainId is 31337')
assert.equal(authProvider.getChainId(), await authProvider.getSigner().getChainId(), 'authProvider signer chainId is 31337')
// Sign the message
const message = 'hihi'
const sig = await signer.signMessage(message, { chainId })
// confirm that authSigner, the chain-bound provider, derived from the authProvider returns the same signature
const authSigner = authProvider.getSigner()
const sigChk = await authSigner.signMessage(message, { chainId })
assert.equal(sigChk, sig, 'authSigner.signMessage returns the same sig')
// Verify the signature
const isValid = await wallet.utils.isValidMessageSignature(address, message, sig, chainId)
assert.true(isValid, 'signAuthMessage, signature is valid')
})
await test('getBalance', async () => {
// technically, the mock-wallet's single signer owner has some ETH..
const balanceSigner1 = await provider.getBalance('0x4e37E14f5d5AAC4DF1151C6E8DF78B7541680853')
assert.true(balanceSigner1.gt(ethers.BigNumber.from(0)), 'signer1 balance > 0')
})
await test('fund sequence wallet', async () => {
// fund Sequence wallet with some ETH from test seed account
const testAccount = getEOAWallet(testAccounts[0].privateKey)
const walletBalanceBefore = await signer.getBalance()
const ethAmount = ethers.utils.parseEther('10.1234')
const txResp = await sendETH(testAccount, wallet.getAddress(), ethAmount)
const txReceipt = await provider.getTransactionReceipt(txResp.hash)
assert.true(txReceipt.status === 1, 'eth sent from signer1')
const walletBalanceAfter = await signer.getBalance()
assert.true(walletBalanceAfter.sub(walletBalanceBefore).eq(ethAmount), `wallet received ${ethAmount} eth`)
})
const testSendETH = async (
title: string,
opts: {
gasLimit?: string
} = {}
) =>
test(title, async () => {
// sequence wallet to now send some eth back to another seed account
// via the relayer
{
const walletAddress = wallet.getAddress()
const walletBalanceBefore = await signer.getBalance()
// send eth from sequence smart wallet to another test account
const toAddress = testAccounts[1].address
const toBalanceBefore = await provider.getBalance(toAddress)
const ethAmount = ethers.utils.parseEther('1.4242')
// NOTE: when a wallet is undeployed (counterfactual), and although the txn contents are to send from our
// sequence wallet to the test account, the transaction by the Sequence Wallet instance will be sent `to` the
// `GuestModule` smart contract address of the Sequence context `from` the Sequence Relayer (local) account.
//
// However, when a wallet is deployed on-chain, and the txn object is to send from our sequence wallet to the
// test account, the transaction will be sent `to` the smart wallet contract address of the sender by
// the relayer. The transaction will then be delegated through the Smart Wallet and transfer will occur
// as an internal transaction on-chain.
//
// Also note, the gasLimit and gasPrice can be estimated by the relayer, or optionally may be specified.
//--
// Record wallet deployed state before, so we can check the receipt.to below. We have to do this
// because a wallet will automatically get bundled for deployment when it sends a transaction.
const beforeWalletDeployed = (await hardhatProvider.getCode(wallet.getAddress())) !== '0x'
// NOTE/TODO: gasPrice even if set will be set again by the LocalRelayer, we should allow it to be overridden
const tx: ethers.providers.TransactionRequest = {
from: walletAddress,
to: toAddress,
value: ethAmount
}
// specifying gasLimit manually
if (opts.gasLimit) {
tx.gasLimit = opts.gasLimit
}
const txResp = await signer.sendTransaction(tx)
const txReceipt = await txResp.wait()
assert.true(txReceipt.status === 1, 'txn sent successfully')
assert.true(
(await hardhatProvider.getCode(wallet.getAddress())) !== '0x',
'wallet must be in deployed state after the txn'
)
// transaction is sent to the deployed wallet, if the wallet is deployed.. otherwise its sent to guestModule
if (beforeWalletDeployed) {
assert.equal(txReceipt.to, wallet.getAddress(), 'recipient is correct')
} else {
assert.equal(txReceipt.to, walletContext[2].guestModule, 'recipient is correct')
}
// Ensure fromAddress sent their eth
const walletBalanceAfter = await signer.getBalance()
const sent = walletBalanceAfter.sub(walletBalanceBefore).mul(-1)
assert.true(sent.eq(ethAmount), `wallet sent ${sent} eth while expected ${ethAmount}`)
// Ensure toAddress received their eth
const toBalanceAfter = await provider.getBalance(toAddress)
const received = toBalanceAfter.sub(toBalanceBefore)
assert.true(received.eq(ethAmount), `toAddress received ${received} eth while expected ${ethAmount}`)
// Extra checks
if (opts.gasLimit) {
// In our test, we are passing a high gas limit for an internal transaction, so overall
// transaction must be higher than this value if it used our value correctly
assert.true(txResp.gasLimit.gte(opts.gasLimit), 'sendETH, using higher gasLimit')
}
}
})
await testSendETH('sendETH (defaultChain)')
// NOTE: this will pass, as we set the gasLimit low on the txn, but the LocalRelayer will re-estimate
// the entire transaction to have it pass.
await testSendETH('sendETH with high gasLimit override (defaultChain)', { gasLimit: '0x55555' })
await test('sendTransaction batch', async () => {
const testAccount = getEOAWallet(testAccounts[1].privateKey)
const ethAmount1 = ethers.utils.parseEther('1.234')
const ethAmount2 = ethers.utils.parseEther('0.456')
const tx1: ethers.providers.TransactionRequest = {
to: testAccount.address,
value: ethAmount1
}
const tx2: ethers.providers.TransactionRequest = {
to: testAccount.address,
value: ethAmount2
}
const toBalanceBefore = await provider.getBalance(testAccount.address)
const txnResp = await signer.sendTransaction([tx1, tx2])
await txnResp.wait()
const toBalanceAfter = await provider.getBalance(testAccount.address)
const sent = toBalanceAfter.sub(toBalanceBefore)
const expected = ethAmount1.add(ethAmount2)
assert.true(
sent.eq(ethAmount1.add(ethAmount2)),
`wallet sent ${sent} eth while expected ${expected} (${ethAmount1} + ${ethAmount2})`
)
})
await test('sendTransaction batch format 2', async () => {
const testAccount = getEOAWallet(testAccounts[1].privateKey)
const ethAmount1 = ethers.utils.parseEther('1.234')
const ethAmount2 = ethers.utils.parseEther('0.456')
const tx1: ethers.providers.TransactionRequest = {
to: testAccount.address,
value: ethAmount1
}
const tx2: ethers.providers.TransactionRequest = {
to: testAccount.address,
value: ethAmount2
}
const toBalanceBefore = await provider.getBalance(testAccount.address)
const txnResp = await signer.sendTransaction([tx1, tx2])
await txnResp.wait()
const toBalanceAfter = await provider.getBalance(testAccount.address)
const sent = toBalanceAfter.sub(toBalanceBefore)
const expected = ethAmount1.add(ethAmount2)
assert.true(
sent.eq(ethAmount1.add(ethAmount2)),
`wallet sent ${sent} eth while expected ${expected} (${ethAmount1} + ${ethAmount2})`
)
})
await test('sendTransaction batch format 3', async () => {
const testAccount = getEOAWallet(testAccounts[1].privateKey)
const ethAmount1 = ethers.utils.parseEther('1.234')
const ethAmount2 = ethers.utils.parseEther('0.456')
const tx1: commons.transaction.Transaction = {
to: testAccount.address,
value: ethAmount1
}
const tx2: commons.transaction.Transaction = {
to: testAccount.address,
value: ethAmount2
}
const toBalanceBefore = await provider.getBalance(testAccount.address)
const txnResp = await signer.sendTransaction([tx1, tx2])
await txnResp.wait()
const toBalanceAfter = await provider.getBalance(testAccount.address)
const sent = toBalanceAfter.sub(toBalanceBefore)
const expected = ethAmount1.add(ethAmount2)
assert.true(
sent.eq(ethAmount1.add(ethAmount2)),
`wallet sent ${sent} eth while expected ${expected} (${ethAmount1} + ${ethAmount2})`
)
})
await test('sendETH from the sequence smart wallet (authChain)', async () => {
// multi-chain to send eth on an alternative chain, in this case the authChain
//
// NOTE: the account addresses are both chains have been seeded with the same private key
// so we can have overlapping addresses and keys for ease of use duringtesting
// get provider of the 2nd chain
const provider2 = wallet.getProvider('hardhat2')!
assert.equal(provider2.getChainId(), 31338, 'provider is the 2nd chain - 1')
assert.equal(provider2.getChainId(), wallet.getProvider(31338)!.getChainId(), 'provider2 code path check')
const signer2 = provider2.getSigner()
// confirm all account addresses are the same and correct
{
assert.equal(wallet.getAddress(), await signer.getAddress(), 'wallet and signer address match')
assert.equal(wallet.getAddress(), await signer2.getAddress(), 'wallet and signer2 address match')
assert.true(wallet.getAddress() !== testAccounts[0].address, 'wallet is not subkey address')
}
// initial balances
{
const testAccount = getEOAWallet(testAccounts[0].privateKey, provider2)
const walletBalanceBefore = await testAccount.getBalance()
const mainTestAccount = getEOAWallet(testAccounts[0].privateKey, wallet.getProvider())
const mainWalletBalanceBefore = await mainTestAccount.getBalance()
assert.true(walletBalanceBefore.toString() !== mainWalletBalanceBefore.toString(), 'balances across networks do not match')
// test different code paths lead to same results
assert.equal(
(await provider2.getBalance(await testAccount.getAddress())).toString(),
(await testAccount.getBalance()).toString(),
'balance match 1'
)
assert.equal(
(await provider.getBalance(await mainTestAccount.getAddress())).toString(),
(await mainTestAccount.getBalance()).toString(),
'balance match 2'
)
}
// first, lets move some ETH info the wallet from teh testnet seed account
{
const testAccount = getEOAWallet(testAccounts[0].privateKey, provider2)
const walletBalanceBefore = await signer2.getBalance()
const ethAmount = ethers.utils.parseEther('4.2')
// const txResp = await sendETH(testAccount, await wallet.getAddress(), ethAmount)
// const txReceipt = await provider2.getTransactionReceipt(txResp.hash)
const txReceipt = await (await sendETH(testAccount, wallet.getAddress(), ethAmount)).wait()
assert.true(txReceipt.status === 1, 'eth sent')
const walletBalanceAfter = await signer2.getBalance()
assert.true(walletBalanceAfter.sub(walletBalanceBefore).eq(ethAmount), `wallet received ${ethAmount} eth`)
}
// using sequence wallet on the authChain, send eth back to anotehr seed account via
// the authChain relayer
{
const walletAddress = wallet.getAddress()
const walletBalanceBefore = await signer2.getBalance()
// send eth from sequence smart wallet to another test account
const toAddress = testAccounts[1].address
const toBalanceBefore = await provider2.getBalance(toAddress)
const ethAmount = ethers.utils.parseEther('1.1234')
const tx = {
from: walletAddress,
to: toAddress,
value: ethAmount
}
const txReceipt = await (await signer2.sendTransaction(tx)).wait()
assert.true(txReceipt.status === 1, 'txn sent successfully')
assert.true((await hardhatProvider.getCode(walletAddress)) !== '0x', 'wallet must be in deployed state after the txn')
// Ensure fromAddress sent their eth
const walletBalanceAfter = await signer2.getBalance()
assert.true(walletBalanceAfter.sub(walletBalanceBefore).mul(-1).eq(ethAmount), `wallet sent ${ethAmount} eth`)
// Ensure toAddress received their eth
const toBalanceAfter = await provider2.getBalance(toAddress)
assert.true(toBalanceAfter.sub(toBalanceBefore).eq(ethAmount), `toAddress received ${ethAmount} eth`)
}
})
}