generated from Borodutch/smart-contract-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arena.sol
697 lines (635 loc) · 19.6 KB
/
Arena.sol
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./models/BattleLobby.sol";
import "./models/Signature.sol";
import "./verifiers/CardSelectionVerifier.sol";
import "./verifiers/CardRevealVerifier.sol";
contract Arena is Ownable {
using Counters for Counters.Counter;
// Contracts
IERC721 public immutable farcantasyContract;
CardSelectionVerifier public immutable cardSelectionVerifierContract;
CardRevealVerifier public immutable cardRevealVerifierContract;
address public immutable attestorEcdsaAddress;
// State
mapping(uint256 => BattleLobby) public battleLobbies;
Counters.Counter public battleLobbyIndex;
// Events
event BattleLobbyCreated(
uint256 indexed lobbyId,
address indexed owner,
uint256[10] ownerCards
);
event BattleLobbyJoined(
uint256 indexed lobbyId,
address indexed participant,
uint256[10] participantCards
);
event BattleLobbyBackedOff(uint256 indexed lobbyId);
event CardSelectionProofSubmitted(
uint256 indexed lobbyId,
address indexed submitter,
uint256 cardSelection
);
event CardsRevealed(
uint256 indexed lobbyId,
address indexed submitter,
uint8[3][3] battleLines
);
event UnusedCardsReturned(
uint256 indexed lobbyId,
address indexed submitter,
uint256[5] unusedCardIds
);
event BattleExecuted(uint256 indexed lobbyId, uint8[3] winners);
event BattleCancelledDueToTimeout(uint256 indexed lobbyId);
constructor(
address _farcantasyContract,
address _cardSelectionVerifierContract,
address _cardRevealVerifierContract,
address _attestorEcdsaAddress
) {
farcantasyContract = IERC721(_farcantasyContract);
cardSelectionVerifierContract = CardSelectionVerifier(
_cardSelectionVerifierContract
);
cardRevealVerifierContract = CardRevealVerifier(
_cardRevealVerifierContract
);
attestorEcdsaAddress = _attestorEcdsaAddress;
}
/**
* Step 1: Create a battle lobby
*/
function createBattleLobby(uint256[10] calldata cardIds) external {
// Check conditions
require(
farcantasyContract.isApprovedForAll(msg.sender, address(this)),
"You must approve the contract to transfer your cards."
);
require(_hasNoDuplicates(cardIds), "CardIds must be unique.");
// Transfer cards from the owner to the contract
for (uint256 i = 0; i < cardIds.length; i++) {
farcantasyContract.safeTransferFrom(
msg.sender,
address(this),
cardIds[i]
);
}
// Create a new battle lobby
BattleLobby memory newLobby = BattleLobby({
lastActivityTimestamp: block.timestamp,
owner: msg.sender,
participant: address(0),
ownerCards: cardIds,
participantCards: [
uint256(0),
uint256(0),
uint256(0),
uint256(0),
uint256(0),
uint256(0),
uint256(0),
uint256(0),
uint256(0),
uint256(0)
],
ownerCardSelection: 0,
participantCardSelection: 0,
isOwnerBattleLinesRevealed: false,
ownerBattleLines: [
[uint8(0), uint8(0), uint8(0)],
[uint8(0), uint8(0), uint8(0)],
[uint8(0), uint8(0), uint8(0)]
],
isParticipantBattleLinesRevealed: false,
participantBattleLines: [
[uint8(0), uint8(0), uint8(0)],
[uint8(0), uint8(0), uint8(0)],
[uint8(0), uint8(0), uint8(0)]
],
battleExecuted: false,
winners: [0, 0, 0]
});
// Add battle lobby to the mapping
battleLobbies[battleLobbyIndex.current()] = newLobby;
// Emit event
emit BattleLobbyCreated(battleLobbyIndex.current(), msg.sender, cardIds);
// Increment battle lobby index
battleLobbyIndex.increment();
}
function _hasNoDuplicates(
uint256[10] memory cardIds
) internal pure returns (bool) {
for (uint256 i = 0; i < cardIds.length; i++) {
for (uint256 j = i + 1; j < cardIds.length; j++) {
if (cardIds[i] == cardIds[j]) {
return false;
}
}
}
return true;
}
/**
* Step 2: Join a battle lobby
*/
function joinBattleLobby(
uint256 lobbyId,
uint256[10] calldata cardIds
) external {
BattleLobby storage lobby = battleLobbies[lobbyId];
// Check conditions
require(_hasNoDuplicates(cardIds), "CardIds must be unique.");
require(
lobby.owner != address(0),
"The specified battle lobby does not exist."
);
require(
lobby.participant == address(0),
"This battle lobby already has a participant."
);
require(
msg.sender != lobby.owner,
"The lobby owner cannot join their own lobby as a participant."
);
require(
farcantasyContract.isApprovedForAll(msg.sender, address(this)),
"You must approve the contract to transfer your cards."
);
// Transfer cards from the participant to the contract
for (uint256 i = 0; i < cardIds.length; i++) {
farcantasyContract.safeTransferFrom(
msg.sender,
address(this),
cardIds[i]
);
}
// Add participant to the battle lobby
lobby.participant = msg.sender;
lobby.participantCards = cardIds;
// Emit event
emit BattleLobbyJoined(lobbyId, msg.sender, cardIds);
// Update last activity timestamp
_updateLastActivityTimestamp(lobbyId);
}
function _transferCardsToOwner(
uint256[10] memory cards,
address owner
) private {
for (uint256 i = 0; i < cards.length; i++) {
if (cards[i] == 0) {
continue;
}
if (farcantasyContract.ownerOf(cards[i]) != address(this)) {
continue;
}
farcantasyContract.safeTransferFrom(address(this), owner, cards[i]);
}
}
function _returnAllCards(BattleLobby memory lobby) private {
// Return all cards to the owner if contract still holds them
_transferCardsToOwner(lobby.ownerCards, lobby.owner);
// Return all cards to the participant if contract still holds them
_transferCardsToOwner(lobby.participantCards, lobby.participant);
}
/**
* Step 2.5: Optional back off for owner
*/
function backOff(uint256 lobbyId) external {
BattleLobby storage lobby = battleLobbies[lobbyId];
// Check conditions
require(
lobby.owner != address(0),
"The specified battle lobby does not exist."
);
require(msg.sender == lobby.owner, "Only the lobby owner can back off.");
require(
lobby.ownerCardSelection == 0,
"The owner has already submitted a card selection."
);
// Return all cards
_returnAllCards(lobby);
// Delete battle lobby
delete battleLobbies[lobbyId];
// Emit event
emit BattleLobbyBackedOff(lobbyId);
}
/**
* Step 3: Submit card selection proof
*/
// Helper function to check if the caller is the owner or participant of the lobby
function _isCallerValid(uint256 lobbyId) internal view returns (bool) {
BattleLobby storage lobby = battleLobbies[lobbyId];
return msg.sender == lobby.owner || msg.sender == lobby.participant;
}
// Helper function to check if the card selection has already been submitted
function _hasCardSelectionBeenSubmitted(
uint256 lobbyId,
bool isOwner
) internal view returns (bool) {
BattleLobby storage lobby = battleLobbies[lobbyId];
uint256 currentCardSelection = isOwner
? lobby.ownerCardSelection
: lobby.participantCardSelection;
return currentCardSelection != 0;
}
function submitCardSelectionProof(
uint256 lobbyId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[1] memory input
) external {
BattleLobby storage lobby = battleLobbies[lobbyId];
bool isOwner = msg.sender == lobby.owner;
// Check conditions
require(
lobby.owner != address(0),
"The specified battle lobby does not exist."
);
require(
lobby.participant != address(0),
"The battle lobby has no participant."
);
require(
_isCallerValid(lobbyId),
"Only the owner or participant can submit a card selection proof."
);
require(
!_hasCardSelectionBeenSubmitted(lobbyId, isOwner),
"Card selection proof has already been submitted."
);
require(
cardSelectionVerifierContract.verifyProof(a, b, c, input),
"The card selection proof is not valid."
);
// Set card selection
if (isOwner) {
lobby.ownerCardSelection = input[0];
} else {
lobby.participantCardSelection = input[0];
}
// Emit event
emit CardSelectionProofSubmitted(lobbyId, msg.sender, input[0]);
// Update last activity timestamp
_updateLastActivityTimestamp(lobbyId);
}
/**
* Step 4: Reveal cards
*/
function revealCards(
uint256 lobbyId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[10] memory input
) external {
BattleLobby storage lobby = battleLobbies[lobbyId];
bool isOwner = msg.sender == lobby.owner;
// Check conditions
require(
lobby.owner != address(0),
"The specified battle lobby does not exist."
);
require(
lobby.participant != address(0),
"The battle lobby has no participant."
);
require(
_isCallerValid(lobbyId),
"Only the owner or participant can submit a card selection proof."
);
require(
lobby.ownerCardSelection != 0 && lobby.participantCardSelection != 0,
"Both card selection proofs must be submitted."
);
require(
cardRevealVerifierContract.verifyProof(a, b, c, input),
"The card reveal proof is not valid."
);
uint256 submittedCardSelection = isOwner
? lobby.ownerCardSelection
: lobby.participantCardSelection;
require(
input[0] == submittedCardSelection,
"The revealed card selection does not match the submitted proof."
);
// Set battle lines and isBattleLinesRevealed
uint8[3][3] memory battleLines;
for (uint8 i = 0; i < 3; i++) {
for (uint8 j = 0; j < 3; j++) {
battleLines[i][j] = uint8(input[1 + i * 3 + j]);
}
}
if (isOwner) {
lobby.ownerBattleLines = battleLines;
lobby.isOwnerBattleLinesRevealed = true;
} else {
lobby.participantBattleLines = battleLines;
lobby.isParticipantBattleLinesRevealed = true;
}
// Emit event
emit CardsRevealed(lobbyId, msg.sender, battleLines);
// Return unused cards
uint256[5] memory unusedCardIds;
uint8 unusedCardCount = 0;
bool[10] memory usedCards;
for (uint8 i = 0; i < 3; i++) {
for (uint8 j = 0; j < 3; j++) {
uint8 usedCardIndex = battleLines[i][j];
if (usedCardIndex != 0) {
usedCards[usedCardIndex - 1] = true;
}
}
}
for (uint8 i = 0; i < 10; i++) {
if (!usedCards[i]) {
uint256 cardId = isOwner
? lobby.ownerCards[i]
: lobby.participantCards[i];
// Add id to unusedCardIds
unusedCardIds[unusedCardCount] = cardId;
unusedCardCount++;
if (unusedCardCount > 4) {
break;
}
}
}
for (uint8 i = 0; i < unusedCardCount; i++) {
farcantasyContract.safeTransferFrom(
address(this),
msg.sender,
unusedCardIds[i]
);
}
// Emit event for unused cards
emit UnusedCardsReturned(lobbyId, msg.sender, unusedCardIds);
// Update last activity timestamp
_updateLastActivityTimestamp(lobbyId);
}
/**
* Step 5: Resolve battle
*/
function _sliceBytes(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
bytes memory tempBytes = new bytes(_length);
for (uint256 i = 0; i < _length; i++) {
tempBytes[i] = _bytes[_start + i];
}
return tempBytes;
}
function _extractDefenceAndOffenceStats(
bytes memory data,
bytes32 r,
bytes32 vs
) internal view returns (uint256 cardId, uint16 offence, uint16 defence) {
// The data is:
// 1. 32 bytes of card id (uint256)
// 2. 2 bytes of offence stats (uint16)
// 3. 2 bytes of defence stats (uint16)
// 4. 32 bytes of timestamp (uint256)
// Verify the signature
(address recoveredAttestorAddress, ECDSA.RecoverError ecdsaError) = ECDSA
.tryRecover(ECDSA.toEthSignedMessageHash(data), r, vs);
require(
ecdsaError == ECDSA.RecoverError.NoError,
"Error while verifying the ECDSA signature"
);
require(
recoveredAttestorAddress == attestorEcdsaAddress,
"Wrong attestor public key"
);
// Extract the timestamp and require it to be less than two days ago
uint256 timestamp = abi.decode(_sliceBytes(data, 36, 32), (uint256));
require(block.timestamp - timestamp <= 2 days, "Timestamp is too old");
// Log offence and defence bytes
bytes memory offenceBytes = _sliceBytes(data, 32, 2);
bytes memory defenceBytes = _sliceBytes(data, 34, 2);
uint16 decodedOffence = uint16(
(uint8(offenceBytes[0]) << 8) | uint8(offenceBytes[1])
);
uint16 decodedDefence = uint16(
(uint8(defenceBytes[0]) << 8) | uint8(defenceBytes[1])
);
// Return the stats
return (
abi.decode(_sliceBytes(data, 0, 32), (uint256)),
decodedOffence,
decodedDefence
);
}
function _transferCards(
uint8[3] memory battleLine,
uint256[10] memory cards,
address to
) private {
for (uint8 j = 0; j < 3; j++) {
uint8 cardIndex = battleLine[j];
if (cardIndex == 0) {
continue;
}
farcantasyContract.safeTransferFrom(
address(this),
to,
cards[cardIndex - 1]
);
}
}
function _checkBattleRequirements(uint256 lobbyId) private view {
BattleLobby storage lobby = battleLobbies[lobbyId];
// Check conditions
require(
lobby.owner != address(0),
"The specified battle lobby does not exist."
);
require(
lobby.participant != address(0),
"The battle lobby has no participant."
);
require(
lobby.isOwnerBattleLinesRevealed &&
lobby.isParticipantBattleLinesRevealed,
"Both battle lines must be revealed."
);
require(!lobby.battleExecuted, "The battle has already been executed.");
}
function _calculateLineOffenceAndDefence(
uint8[3] memory battleLines,
Signature[3] memory lineStats,
uint256[10] memory cards
) private view returns (uint16 offence, uint16 defence) {
for (uint8 i = 0; i < 3; i++) {
// If the card is not present, skip
if (battleLines[i] == 0) {
continue;
}
// Get card stats
(
uint256 cardId,
uint16 cardOffence,
uint16 cardDefence
) = _extractDefenceAndOffenceStats(
lineStats[i].data,
lineStats[i].r,
lineStats[i].vs
);
uint8 cardIndex = battleLines[i] - 1;
require(
cardId == cards[cardIndex],
"The card id does not match the submitted battle line."
);
offence += cardOffence;
defence += cardDefence;
}
}
function _selectWinner(
uint16 ownerLineOffence,
uint16 ownerLineDefence,
uint16 participantLineOffence,
uint16 participantLineDefence
) private pure returns (uint8) {
int16 ownerScore = int16(ownerLineDefence) - int16(participantLineOffence);
int16 participantScore = int16(participantLineDefence) -
int16(ownerLineOffence);
int16 scoreDifference = ownerScore - participantScore;
// 0 — No winner, 1 — Owner, 2 — Participant
return (scoreDifference > 0) ? 1 : ((scoreDifference < 0) ? 2 : 0);
}
function _calculateWinners(
uint256 lobbyId,
Signature[3][3][2] memory stats
) private view returns (uint8[3] memory) {
BattleLobby storage lobby = battleLobbies[lobbyId];
uint8[3] memory winners;
Signature[3][3] memory ownerStats = stats[0];
Signature[3][3] memory participantStats = stats[1];
for (uint8 i = 0; i < 3; i++) {
// Calculate owner and participant offence and defence
(
uint16 ownerLineOffence,
uint16 ownerLineDefence
) = _calculateLineOffenceAndDefence(
lobby.ownerBattleLines[i],
ownerStats[i],
lobby.ownerCards
);
(
uint16 participantLineOffence,
uint16 participantLineDefence
) = _calculateLineOffenceAndDefence(
lobby.participantBattleLines[i],
participantStats[i],
lobby.participantCards
);
// Select the winner
winners[i] = _selectWinner(
ownerLineOffence,
ownerLineDefence,
participantLineOffence,
participantLineDefence
);
}
return winners;
}
function executeBattle(
uint256 lobbyId,
Signature[3][3][2] memory stats
) external {
// Check conditions
_checkBattleRequirements(lobbyId);
// Execute battle
uint8[3] memory winners = _calculateWinners(lobbyId, stats);
// Transfer cards depending on winners
BattleLobby storage lobby = battleLobbies[lobbyId];
for (uint8 i = 0; i < 3; i++) {
uint8 winner = winners[i];
address ownerCardsReceipient = (winner == 0 || winner == 1)
? lobby.owner
: lobby.participant;
address participantCardsReceipient = (winner == 0 || winner == 2)
? lobby.participant
: lobby.owner;
_transferCards(
lobby.ownerBattleLines[i],
lobby.ownerCards,
ownerCardsReceipient
);
_transferCards(
lobby.participantBattleLines[i],
lobby.participantCards,
participantCardsReceipient
);
}
// Emit event
emit BattleExecuted(lobbyId, winners);
// Delete the lobby for gas refund
delete battleLobbies[lobbyId];
}
/**
* Helpers
*/
function getOwnerBattleLines(
uint256 lobbyId
) external view returns (uint8[3][3] memory) {
return battleLobbies[lobbyId].ownerBattleLines;
}
function getParticipantBattleLines(
uint256 lobbyId
) external view returns (uint8[3][3] memory) {
return battleLobbies[lobbyId].participantBattleLines;
}
/**
* Admin functions
*/
// Emergency function to withdraw cards from the contract to the owner
function withdrawCards(uint256[] memory cardIds) external onlyOwner {
for (uint256 i = 0; i < cardIds.length; i++) {
farcantasyContract.safeTransferFrom(address(this), owner(), cardIds[i]);
}
}
/**
* Timeout functions
*/
function _updateLastActivityTimestamp(uint256 lobbyId) private {
require(
battleLobbies[lobbyId].owner != address(0),
"The specified battle lobby does not exist."
);
battleLobbies[lobbyId].lastActivityTimestamp = block.timestamp;
}
function hasTimedOut(uint256 lobbyId) public view returns (bool) {
uint256 timeoutDuration = 2 days;
return
block.timestamp >
battleLobbies[lobbyId].lastActivityTimestamp + timeoutDuration;
}
function cancelDueToTimeout(uint256 lobbyId) external {
BattleLobby storage lobby = battleLobbies[lobbyId];
// Check requirements
require(
lobby.owner != address(0),
"The specified battle lobby does not exist."
);
require(
msg.sender == lobby.owner ||
msg.sender == lobby.participant ||
msg.sender == owner(),
"Only the owner, the participant or the contract owner can cancel the battle lobby."
);
require(!lobby.battleExecuted, "The battle has already been executed.");
require(hasTimedOut(lobbyId), "The battle lobby has not timed out yet.");
// Return all cards
_returnAllCards(lobby);
// Emit event
emit BattleCancelledDueToTimeout(lobbyId);
// Delete the lobby for gas refund
delete battleLobbies[lobbyId];
}
}