-
Notifications
You must be signed in to change notification settings - Fork 18
/
atomicswap.spec.ts
482 lines (416 loc) · 17.9 KB
/
atomicswap.spec.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
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
import {
Address,
Amount,
AtomicSwap,
AtomicSwapConnection,
AtomicSwapHelpers,
ClaimedSwap,
Identity,
isBlockInfoPending,
isBlockInfoSucceeded,
isClaimedSwap,
isOpenSwap,
OpenSwap,
Preimage,
SendTransaction,
SwapClaimTransaction,
SwapOfferTransaction,
SwapProcessState,
TokenTicker,
UnsignedTransaction,
} from "@iov/bcp";
import { HdPaths, Secp256k1HdWallet, UserProfile } from "@iov/keycontrol";
import BN from "bn.js";
import { Erc20ApproveTransaction } from "../erc20";
import { EthereumCodec } from "../ethereumcodec";
import { EthereumConnection } from "../ethereumconnection";
import { SwapIdPrefix } from "../serializationcommon";
import { testConfig } from "../testconfig.spec";
const ETH = "ETH" as TokenTicker;
const ASH = "ASH" as TokenTicker;
const ethereumCodec = new EthereumCodec({
atomicSwapEtherContractAddress: testConfig.connectionOptions.atomicSwapEtherContractAddress,
atomicSwapErc20ContractAddress: testConfig.connectionOptions.atomicSwapErc20ContractAddress,
erc20Tokens: testConfig.erc20Tokens,
});
function pendingWithoutEthereum(): void {
if (!process.env.ETHEREUM_ENABLED) {
return pending("Set ETHEREUM_ENABLED to enable ethereum-node-based tests");
}
}
interface ActorData {
readonly profile: UserProfile;
readonly connection: AtomicSwapConnection;
readonly senderIdentity: Identity;
readonly receiverIdentity: Identity;
}
class Actor {
public static async create(mnemonic: string, addressIndex1: number, addressIndex2: number): Promise<Actor> {
const profile = new UserProfile();
const wallet = profile.addWallet(Secp256k1HdWallet.fromMnemonic(mnemonic));
const connection: AtomicSwapConnection = await EthereumConnection.establish(testConfig.baseHttp, {
...testConfig.connectionOptions,
erc20Tokens: testConfig.erc20Tokens,
});
const path1 = HdPaths.ethereum(addressIndex1);
const path2 = HdPaths.ethereum(addressIndex2);
const senderIdentity = await profile.createIdentity(wallet.id, connection.chainId, path1);
const receiverIdentity = await profile.createIdentity(wallet.id, connection.chainId, path2);
return new Actor({
profile: profile,
connection: connection,
senderIdentity: senderIdentity,
receiverIdentity: receiverIdentity,
});
}
public readonly senderIdentity: Identity;
public readonly receiverIdentity: Identity;
public get sendAddress(): Address {
return ethereumCodec.identityToAddress(this.senderIdentity);
}
public get receiveAddress(): Address {
return ethereumCodec.identityToAddress(this.receiverIdentity);
}
private readonly profile: UserProfile;
private readonly connection: AtomicSwapConnection;
// tslint:disable-next-line:readonly-keyword
private preimage?: Preimage;
public constructor(data: ActorData) {
this.profile = data.profile;
this.connection = data.connection;
this.senderIdentity = data.senderIdentity;
this.receiverIdentity = data.receiverIdentity;
}
public async sendTransaction(transaction: UnsignedTransaction, identity: Identity): Promise<void> {
const nonce = await this.connection.getNonce({ pubkey: identity.pubkey });
const signed = await this.profile.signTransaction(identity, transaction, ethereumCodec, nonce);
const postable = ethereumCodec.bytesToPost(signed);
const post = await this.connection.postTx(postable);
const blockInfo = await post.blockInfo.waitFor((info) => !isBlockInfoPending(info));
if (!isBlockInfoSucceeded(blockInfo)) {
throw new Error("Transaction failed");
}
}
public async sendEther(recipient: Address, amount: Amount): Promise<void> {
const transaction = await this.connection.withDefaultFee<SendTransaction>({
kind: "bcp/send",
chainId: this.senderIdentity.chainId,
sender: ethereumCodec.identityToAddress(this.senderIdentity),
recipient: recipient,
amount: amount,
});
return this.sendTransaction(transaction, this.senderIdentity);
}
public async approveErc20Spend(amount: Amount): Promise<void> {
const transaction = await this.connection.withDefaultFee<Erc20ApproveTransaction>({
kind: "erc20/approve",
chainId: this.senderIdentity.chainId,
spender: testConfig.connectionOptions.atomicSwapErc20ContractAddress!,
amount: amount,
});
return this.sendTransaction(transaction, this.senderIdentity);
}
public async getSenderEtherBalance(): Promise<BN> {
const account = await this.connection.getAccount({ pubkey: this.senderIdentity.pubkey });
const balance = account ? account.balance : [];
const amount = balance.find((row) => row.tokenTicker === ETH);
return new BN(amount ? amount.quantity : 0);
}
public async getReceiverEtherBalance(): Promise<BN> {
const account = await this.connection.getAccount({ pubkey: this.receiverIdentity.pubkey });
const balance = account ? account.balance : [];
const amount = balance.find((row) => row.tokenTicker === ETH);
return new BN(amount ? amount.quantity : 0);
}
public async getSenderErc20Balance(): Promise<BN> {
const account = await this.connection.getAccount({ pubkey: this.senderIdentity.pubkey });
const balance = account ? account.balance : [];
const amount = balance.find((row) => row.tokenTicker === ASH);
return new BN(amount ? amount.quantity : 0);
}
public async getReceiverErc20Balance(): Promise<BN> {
const account = await this.connection.getAccount({ pubkey: this.receiverIdentity.pubkey });
const balance = account ? account.balance : [];
const amount = balance.find((row) => row.tokenTicker === ASH);
return new BN(amount ? amount.quantity : 0);
}
public async getReceiverSwaps(): Promise<readonly AtomicSwap[]> {
return this.connection.getSwaps({ recipient: this.receiveAddress });
}
public async getSenderSwaps(): Promise<readonly AtomicSwap[]> {
return this.connection.getSwaps({ sender: this.sendAddress });
}
public async generatePreimage(): Promise<void> {
// tslint:disable-next-line:no-object-mutation
this.preimage = await AtomicSwapHelpers.createPreimage();
}
public async sendSwapOffer(recipient: Address, amount: Amount): Promise<void> {
const swapId = await (amount.tokenTicker === ETH
? EthereumConnection.createEtherSwapId()
: EthereumConnection.createErc20SwapId());
const transaction = await this.connection.withDefaultFee<SwapOfferTransaction>({
kind: "bcp/swap_offer",
chainId: this.senderIdentity.chainId,
sender: this.sendAddress,
recipient: recipient,
amounts: [amount],
swapId: swapId,
hash: AtomicSwapHelpers.hashPreimage(this.preimage!),
timeout: {
height: (await this.connection.height()) + 50,
},
});
return this.sendTransaction(transaction, this.senderIdentity);
}
public async sendSwapCounter(recipient: Address, amount: Amount, offer: AtomicSwap): Promise<void> {
const swapId = await (amount.tokenTicker === ETH
? EthereumConnection.createEtherSwapId()
: EthereumConnection.createErc20SwapId());
const transaction = await this.connection.withDefaultFee<SwapOfferTransaction>({
kind: "bcp/swap_offer",
chainId: this.senderIdentity.chainId,
sender: this.sendAddress,
recipient: recipient,
amounts: [amount],
swapId: swapId,
hash: offer.data.hash,
timeout: {
height: (await this.connection.height()) + 50,
},
});
return this.sendTransaction(transaction, this.senderIdentity);
}
public async claimFromKnownPreimage(counter: AtomicSwap): Promise<void> {
const transaction = await this.connection.withDefaultFee<SwapClaimTransaction>({
kind: "bcp/swap_claim",
chainId: this.receiverIdentity.chainId,
swapId: counter.data.id,
preimage: this.preimage!,
});
return this.sendTransaction(transaction, this.receiverIdentity);
}
public async claimFromRevealedPreimage(offer: OpenSwap, claimed: ClaimedSwap): Promise<void> {
const transaction = await this.connection.withDefaultFee<SwapClaimTransaction>({
kind: "bcp/swap_claim",
chainId: this.receiverIdentity.chainId,
swapId: offer.data.id,
preimage: claimed.preimage,
});
return this.sendTransaction(transaction, this.receiverIdentity);
}
}
describe("Full atomic swap", () => {
// TODO: handle different fees... right now assumes the same fee is used for all send txs
it("works for Ether", async () => {
pendingWithoutEthereum();
const alice = await Actor.create(testConfig.mnemonic, 0, 100);
expect(alice.sendAddress).toEqual("0x88F3b5659075D0E06bB1004BE7b1a7E66F452284");
expect(alice.receiveAddress).toEqual("0x3DD3246a7a0D3b31D07379b0C422556637Bc0e20");
const bob = await Actor.create(testConfig.mnemonic, 2, 102);
expect(bob.sendAddress).toEqual("0x585ec8C463C8f9481f606456402cE7CACb8D2d2A");
expect(bob.receiveAddress).toEqual("0x25e50d0DF784d81edD11d4D70FbaBD3Ade0C6811");
// We need to send some tokens to the other ones to allow claim fees
const claimQuantity = "42000000000000000";
await alice.sendEther(alice.receiveAddress, {
quantity: claimQuantity,
fractionalDigits: 18,
tokenTicker: ETH,
});
await bob.sendEther(bob.receiveAddress, {
quantity: claimQuantity,
fractionalDigits: 18,
tokenTicker: ETH,
});
// Alice has ETH in her sender account but not receiver account
const aliceInitialSender = await alice.getSenderEtherBalance();
const aliceInitialReceiver = await alice.getReceiverEtherBalance();
expect(aliceInitialSender.gtn(100_000_000_000_000_000_000)).toEqual(true);
// Bob has ETH in his sender account but not receiver account
const bobInitialSender = await bob.getSenderEtherBalance();
const bobInitialReceiver = await bob.getReceiverEtherBalance();
expect(bobInitialSender.gtn(100_000_000_000_000_000_000)).toEqual(true);
// A secret that only Alice knows
await alice.generatePreimage();
await alice.sendSwapOffer(bob.receiveAddress, {
quantity: "2000000000000000000",
fractionalDigits: 18,
tokenTicker: ETH,
});
// Alice's Ether are locked in the contract (also includes fee)
expect(
aliceInitialSender.sub(await alice.getSenderEtherBalance()).gtn(2_000_000_000_000_000_000),
).toEqual(true);
// review offer
const bobReceiverSwaps = (await bob.getReceiverSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Ether,
);
const aliceOffer = bobReceiverSwaps[bobReceiverSwaps.length - 1];
expect(aliceOffer.kind).toEqual(SwapProcessState.Open);
expect(aliceOffer.data.recipient).toEqual(bob.receiveAddress);
expect(aliceOffer.data.amounts.length).toEqual(1);
expect(aliceOffer.data.amounts[0]).toEqual({
quantity: "2000000000000000000",
fractionalDigits: 18,
tokenTicker: ETH,
});
await bob.sendSwapCounter(
alice.receiveAddress,
{
quantity: "5000000000000000000",
fractionalDigits: 18,
tokenTicker: ETH,
},
aliceOffer,
);
// Bob's Ether are locked in the contract (also includes fee)
expect(bobInitialSender.sub(await bob.getSenderEtherBalance()).gtn(5_000_000_000_000_000_000)).toEqual(
true,
);
// review counteroffer
const aliceReceiverSwaps = (await alice.getReceiverSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Ether,
);
const counter = aliceReceiverSwaps[aliceReceiverSwaps.length - 1];
expect(counter.kind).toEqual(SwapProcessState.Open);
expect(counter.data.recipient).toEqual(alice.receiveAddress);
expect(counter.data.amounts.length).toEqual(1);
expect(counter.data.amounts[0]).toEqual({
quantity: "5000000000000000000",
fractionalDigits: 18,
tokenTicker: ETH,
});
await alice.claimFromKnownPreimage(counter);
// Alice revealed her secret and should unlock the funds
expect(
(await alice.getReceiverEtherBalance()).sub(aliceInitialReceiver).gtn(4_900_000_000_000_000_000),
).toEqual(true);
// find claim
const bobSenderSwaps = (await bob.getSenderSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Ether,
);
const aliceClaimed = bobSenderSwaps[bobSenderSwaps.length - 1];
if (!isClaimedSwap(aliceClaimed)) {
throw new Error("Expected swap to be claimed");
}
const bobReceiverSwaps2 = (await bob.getReceiverSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Ether,
);
const aliceOffer2 = bobReceiverSwaps2[bobReceiverSwaps2.length - 1];
if (!isOpenSwap(aliceOffer2)) {
throw new Error("Expected swap to be open");
}
await bob.claimFromRevealedPreimage(aliceOffer2, aliceClaimed);
// Bob used Alice's preimage to claim unlock his funds
expect(
(await bob.getReceiverEtherBalance()).sub(bobInitialReceiver).gtn(4_900_000_000_000_000_000),
).toEqual(true);
// Alice and Bob's funds were not returned to sender
expect(
aliceInitialSender.sub(await alice.getSenderEtherBalance()).gtn(2_000_000_000_000_000_000),
).toEqual(true);
expect(bobInitialSender.sub(await bob.getSenderEtherBalance()).gtn(5_000_000_000_000_000_000)).toEqual(
true,
);
}, 30_000);
it("works for ERC20", async () => {
pendingWithoutEthereum();
const alice = await Actor.create(testConfig.mnemonic, 0, 100);
expect(alice.sendAddress).toEqual("0x88F3b5659075D0E06bB1004BE7b1a7E66F452284");
expect(alice.receiveAddress).toEqual("0x3DD3246a7a0D3b31D07379b0C422556637Bc0e20");
const bob = await Actor.create(testConfig.mnemonic, 2, 102);
expect(bob.sendAddress).toEqual("0x585ec8C463C8f9481f606456402cE7CACb8D2d2A");
expect(bob.receiveAddress).toEqual("0x25e50d0DF784d81edD11d4D70FbaBD3Ade0C6811");
// We need to send some Ether to the other ones to allow claim fees
const claimQuantity = "42000000000000000";
await alice.sendEther(alice.receiveAddress, {
quantity: claimQuantity,
fractionalDigits: 18,
tokenTicker: ETH,
});
await bob.sendEther(bob.receiveAddress, {
quantity: claimQuantity,
fractionalDigits: 18,
tokenTicker: ETH,
});
// Alice has ASH in her sender account but not receiver account
const aliceInitialSender = await alice.getSenderErc20Balance();
const aliceInitialReceiver = await alice.getReceiverErc20Balance();
expect(aliceInitialSender.gt(new BN(10_000_000))).toEqual(true);
// Bob has ASH in his sender account but not receiver account
const bobInitialSender = await bob.getSenderErc20Balance();
const bobInitialReceiver = await bob.getReceiverErc20Balance();
expect(bobInitialSender.gt(new BN(10_000_000))).toEqual(true);
// A secret that only Alice knows
await alice.generatePreimage();
const aliceOfferAmount: Amount = {
quantity: "2000000",
fractionalDigits: 12,
tokenTicker: ASH,
};
await alice.approveErc20Spend(aliceOfferAmount);
await alice.sendSwapOffer(bob.receiveAddress, aliceOfferAmount);
// Alice's ASH are locked in the contract
expect(aliceInitialSender.sub(await alice.getSenderErc20Balance()).eq(new BN(2_000_000))).toEqual(true);
// review offer
const bobReceiverSwaps = (await bob.getReceiverSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Erc20,
);
const aliceOffer = bobReceiverSwaps[bobReceiverSwaps.length - 1];
expect(aliceOffer.kind).toEqual(SwapProcessState.Open);
expect(aliceOffer.data.recipient).toEqual(bob.receiveAddress);
expect(aliceOffer.data.amounts.length).toEqual(1);
expect(aliceOffer.data.amounts[0]).toEqual({
quantity: "2000000",
fractionalDigits: 12,
tokenTicker: ASH,
});
const bobCounterAmount: Amount = {
quantity: "5000000",
fractionalDigits: 12,
tokenTicker: ASH,
};
await bob.approveErc20Spend(bobCounterAmount);
await bob.sendSwapCounter(alice.receiveAddress, bobCounterAmount, aliceOffer);
// Bob's ASH are locked in the contract
expect(bobInitialSender.sub(await bob.getSenderErc20Balance()).eq(new BN(5_000_000))).toEqual(true);
// review counteroffer
const aliceReceiverSwaps = (await alice.getReceiverSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Erc20,
);
const counter = aliceReceiverSwaps[aliceReceiverSwaps.length - 1];
expect(counter.kind).toEqual(SwapProcessState.Open);
expect(counter.data.recipient).toEqual(alice.receiveAddress);
expect(counter.data.amounts.length).toEqual(1);
expect(counter.data.amounts[0]).toEqual({
quantity: "5000000",
fractionalDigits: 12,
tokenTicker: ASH,
});
await alice.claimFromKnownPreimage(counter);
// Alice revealed her secret and should unlock the funds
expect((await alice.getReceiverErc20Balance()).sub(aliceInitialReceiver).eq(new BN(5_000_000))).toEqual(
true,
);
// find claim
const bobSenderSwaps = (await bob.getSenderSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Erc20,
);
const aliceClaimed = bobSenderSwaps[bobSenderSwaps.length - 1];
if (!isClaimedSwap(aliceClaimed)) {
throw new Error("Expected swap to be claimed");
}
const bobReceiverSwaps2 = (await bob.getReceiverSwaps()).filter(
(swap) => swap.data.id.prefix === SwapIdPrefix.Erc20,
);
const aliceOffer2 = bobReceiverSwaps2[bobReceiverSwaps2.length - 1];
if (!isOpenSwap(aliceOffer2)) {
throw new Error("Expected swap to be open");
}
await bob.claimFromRevealedPreimage(aliceOffer2, aliceClaimed);
// Bob used Alice's preimage to claim unlock his funds
expect((await bob.getReceiverErc20Balance()).sub(bobInitialReceiver).eq(new BN(2_000_000))).toEqual(true);
// Alice and Bob's funds were not returned to sender
expect(aliceInitialSender.sub(await alice.getSenderErc20Balance()).eq(new BN(2_000_000))).toEqual(true);
expect(bobInitialSender.sub(await bob.getSenderErc20Balance()).eq(new BN(5_000_000))).toEqual(true);
}, 30_000);
});