generated from z0r0z/zenplate
-
Notifications
You must be signed in to change notification settings - Fork 6
/
IE.sol
1523 lines (1382 loc) · 55.6 KB
/
IE.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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.19;
import {SafeTransferLib} from "../lib/solady/src/utils/SafeTransferLib.sol";
import {MetadataReaderLib} from "../lib/solady/src/utils/MetadataReaderLib.sol";
/// @title Intents Engine (IE) on Arbitrum
/// @notice Simple helper contract for turning transactional intents into executable code.
/// @dev V2 simulates typical commands (sending and swapping tokens) and includes execution.
/// IE also has a workflow to verify the intent of ERC4337 account userOps against calldata.
/// @author nani.eth (https://github.com/NaniDAO/ie)
/// @custom:version 2.3.0
contract IE {
/// ======================= LIBRARY USAGE ======================= ///
/// @dev Token transfer library.
using SafeTransferLib for address;
/// @dev Token metadata reader library.
using MetadataReaderLib for address;
/// ======================= CUSTOM ERRORS ======================= ///
/// @dev Bad math.
error Overflow();
/// @dev 0-liquidity.
error InvalidSwap();
/// @dev Invalid command.
error InvalidSyntax();
/// @dev Invalid out receiver.
error InvalidReceiver();
/// @dev Non-numeric character.
error InvalidCharacter();
/// @dev Invalid function caller.
error Unauthorized();
/// @dev Order expiry has arrived.
error OrderExpired();
/// @dev Insufficient swap output.
error InsufficientSwap();
/// @dev Invalid selector for spend.
error InvalidSelector();
/// @dev Unauthorized reentrant call.
error Reentrancy();
/// =========================== EVENTS =========================== ///
/// @dev Logs the setting of a token name.
event NameSet(address token, string name);
/// @dev Logs the setting of a swap pool pair on Uniswap V3.
event PairSet(address token0, address token1, address pair);
/// ========================== STRUCTS ========================== ///
/// @dev The packed ERC4337 user operation (userOp) struct.
struct PackedUserOperation {
address sender;
uint256 nonce;
bytes initCode;
bytes callData;
bytes32 accountGasLimits;
uint256 preVerificationGas;
bytes32 gasFees;
bytes paymasterAndData;
bytes signature;
}
/// @dev The `swap()` command information struct.
struct SwapInfo {
bool ETHIn;
bool ETHOut;
address tokenIn;
address tokenOut;
uint256 amountIn;
}
/// @dev The `swap()` pool liquidity struct.
struct SwapLiq {
address pool;
uint256 liq;
}
/// @dev The string start and end indices.
struct StringPart {
uint256 start;
uint256 end;
}
/// @dev The onchain order struct.
struct Order {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOut;
address maker;
address receiver;
uint48 nonce;
uint48 expiry;
}
/// ========================= CONSTANTS ========================= ///
/// @dev The governing DAO address.
address internal constant DAO = 0xDa000000000000d2885F108500803dfBAaB2f2aA;
/// @dev The conventional ERC7528 ETH address.
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev The canonical wrapped ETH address.
address internal constant WETH = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1;
/// @dev The popular wrapped BTC address.
address internal constant WBTC = 0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f;
/// @dev The Circle USD stablecoin address.
address internal constant USDC = 0xaf88d065e77c8cC2239327C5EDb3A432268e5831;
/// @dev The Tether USD stablecoin address.
address internal constant USDT = 0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9;
/// @dev The Maker DAO USD stablecoin address.
address internal constant DAI = 0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1;
/// @dev The Arbitrum DAO governance token address.
address internal constant ARB = 0x912CE59144191C1204E64559FE8253a0e49E6548;
/// @dev The Lido Wrapped Staked ETH token address.
address internal constant WSTETH = 0x5979D7b546E38E414F7E9822514be443A4800529;
/// @dev The Rocket Pool Staked ETH token address.
address internal constant RETH = 0xEC70Dcb4A1EFa46b8F2D97C310C9c4790ba5ffA8;
/// @dev The resolution registry smart account.
address internal constant CURIA = 0x0000000000001d8a2e7bf6bc369525A2654aa298;
/// @dev The Escrows protocol singleton.
address internal constant ESCROWS = 0x00000000000044992CB97CB1A57A32e271C04c11;
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
uint256 internal constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/// @dev The address of the Uniswap V3 Factory.
address internal constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
/// @dev The Uniswap V3 Pool `initcodehash`.
bytes32 internal constant UNISWAP_V3_POOL_INIT_CODE_HASH =
0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @dev The minimum value that can be returned from `getSqrtRatioAtTick` (plus one).
uint160 internal constant MIN_SQRT_RATIO_PLUS_ONE = 4295128740;
/// @dev The maximum value that can be returned from `getSqrtRatioAtTick` (minus one).
uint160 internal constant MAX_SQRT_RATIO_MINUS_ONE =
1461446703485210103287273052203988822378723970341;
/// ========================== STORAGE ========================== ///
/// @dev DAO-governed naming interface (nami).
INAMI internal nami;
/// @dev DAO-governed token names to addresses.
mapping(string name => address) public addresses;
/// @dev DAO-governed token addresses to names.
mapping(address addresses => string) public names;
/// @dev Open order book for p2p asset exchange.
mapping(bytes32 orderHash => Order) public orders;
/// @dev DAO-governed token swap pool routing on Uniswap V3.
mapping(address token0 => mapping(address token1 => address)) public pairs;
/// @dev Array of onchain order struct hashes.
bytes32[] public orderHashes;
/// ======================== CONSTRUCTOR ======================== ///
/// @dev Constructs this IE on the Arbitrum L2 of Ethereum.
constructor() payable {}
/// ====================== COMMAND PREVIEW ====================== ///
/// @dev Preview natural language smart contract command.
/// The `send` syntax uses ENS naming: 'send vitalik 20 DAI'.
/// `swap` syntax uses common format: 'swap 100 DAI for WETH'.
/// `lock` syntax uses send format: 'lock 1 WETH for vitalik'.
function previewCommand(string calldata intent)
public
view
virtual
returns (
address to, // Receiver address.
uint256 amount, // Formatted amount.
uint256 minAmountOut, // Formatted amount.
address token, // Asset to send `to`.
bytes memory callData, // Raw calldata for send transaction.
bytes memory executeCallData // Anticipates common execute API.
)
{
bytes memory normalized = _lowercase(bytes(intent));
bytes32 action = _extraction(normalized);
if (action == "send" || action == "transfer" || action == "pay" || action == "grant") {
(bytes memory _to, bytes memory _amount, bytes memory _token) = _extractSend(normalized);
(to, amount, token, callData, executeCallData) = _previewSend(_to, _amount, _token);
} else if (
action == "swap" || action == "sell" || action == "exchange" || action == "stake"
) {
(
bytes memory amountIn,
bytes memory amountOutMin,
bytes memory tokenIn,
bytes memory tokenOut,
bytes memory receiver
) = _extractSwap(normalized);
address _receiver;
(amount, minAmountOut, token, to, _receiver) =
_previewSwap(amountIn, amountOutMin, tokenIn, tokenOut, receiver);
callData = abi.encodePacked(_receiver);
} else if (action == "lock" || action == "lockup" || action == "escrow") {
(
bytes memory _to,
bytes memory _amount,
bytes memory _token,
bytes memory _time,
bytes memory _unit
) = _extractLock(normalized);
(to, amount, token, minAmountOut /*expiry*/ ) =
_previewLock(_to, _amount, _token, _time, _unit);
} else if (action == "order") {
(
bytes memory amountIn,
bytes memory amountOut,
bytes memory tokenIn,
bytes memory tokenOut,
bytes memory receiver
) = _extractSwap(normalized);
address _receiver;
(amount, minAmountOut, token, to, _receiver) =
_previewSwap(amountIn, amountOut, tokenIn, tokenOut, receiver);
callData = abi.encodePacked(_receiver);
} else {
revert InvalidSyntax(); // Invalid command format.
}
}
/// @dev Previews a `send` command from the parts of a matched intent string.
function _previewSend(bytes memory to, bytes memory amount, bytes memory token)
internal
view
virtual
returns (
address _to,
uint256 _amount,
address _token,
bytes memory callData,
bytes memory executeCallData
)
{
uint256 decimals;
if (token.length == 42) _token = _toAddress(token);
else (_token, decimals) = _returnTokenConstants(bytes32(token));
if (_token == address(0)) _token = addresses[string(token)];
bool isETH = _token == ETH;
(, _to,) = whatIsTheAddressOf(string(to));
_amount = _toUint(amount, decimals != 0 ? decimals : _token.readDecimals(), _token);
if (!isETH) callData = abi.encodeCall(IToken.transfer, (_to, _amount));
executeCallData =
abi.encodeCall(IExecutor.execute, (isETH ? _to : _token, isETH ? _amount : 0, callData));
}
/// @dev Previews a `lock` command from the parts of a matched intent string.
function _previewLock(
bytes memory to,
bytes memory amount,
bytes memory token,
bytes memory time,
bytes memory unit
)
internal
view
virtual
returns (address _to, uint256 _amount, address _token, uint256 _expiry)
{
uint256 decimals;
if (token.length == 42) _token = _toAddress(token);
else (_token, decimals) = _returnTokenConstants(bytes32(token));
if (_token == address(0)) _token = addresses[string(token)];
(, _to,) = whatIsTheAddressOf(string(to));
_amount = _toUint(amount, decimals != 0 ? decimals : _token.readDecimals(), _token);
uint256 _time = _simpleToUint256(time);
bytes32 _unit = bytes32(unit);
unchecked {
if (_unit == "minute" || _unit == "minutes") {
_time = _time * 1 minutes;
} else if (_unit == "day" || _unit == "days") {
_time = _time * 1 days;
} else if (_unit == "week" || _unit == "weeks") {
_time = _time * 1 weeks;
} else if (_unit == "month" || _unit == "months") {
_time = _time * 4 weeks;
} else if (_unit == "year" || _unit == "years") {
_time = _time * 52 weeks;
} else {
revert InvalidSyntax(); // Invalid `unit`.
}
_expiry = block.timestamp + _time;
}
}
/// @dev Previews a `swap` command from the parts of a matched intent string.
function _previewSwap(
bytes memory amountIn,
bytes memory amountOutMin,
bytes memory tokenIn,
bytes memory tokenOut,
bytes memory receiver
)
internal
view
virtual
returns (
uint256 _amountIn,
uint256 _amountOut,
address _tokenIn,
address _tokenOut,
address _receiver
)
{
uint256 decimalsIn;
uint256 decimalsOut;
if (tokenIn.length == 42) _tokenIn = _toAddress(tokenIn);
else (_tokenIn, decimalsIn) = _returnTokenConstants(bytes32(tokenIn));
if (_tokenIn == address(0)) _tokenIn = addresses[string(tokenIn)];
if (tokenOut.length == 42) _tokenOut = _toAddress(tokenOut);
else (_tokenOut, decimalsOut) = _returnTokenConstants(bytes32(tokenOut));
if (_tokenOut == address(0)) _tokenOut = addresses[string(tokenOut)];
_amountIn =
_toUint(amountIn, decimalsIn != 0 ? decimalsIn : _tokenIn.readDecimals(), _tokenIn);
_amountOut = _toUint(
amountOutMin, decimalsOut != 0 ? decimalsOut : _tokenOut.readDecimals(), _tokenOut
);
if (receiver.length != 0) (, _receiver,) = whatIsTheAddressOf(string(receiver));
}
/// @dev Checks packed ERC4337 userOp against the output of the command intent.
/// note: This function checks ETH and ERC20 transfers only with `execute()`.
function checkUserOp(string calldata intent, PackedUserOperation calldata userOp)
public
view
virtual
returns (bool intentMatched)
{
(,,,,, bytes memory executeCallData) = previewCommand(intent);
if (executeCallData.length != userOp.callData.length) return false;
return keccak256(executeCallData) == keccak256(userOp.callData);
}
/// @dev Checks and returns the canonical token address constant for a matched intent string.
function _returnTokenConstants(bytes32 token)
internal
pure
virtual
returns (address _token, uint256 _decimals)
{
if (token == "eth" || token == "ether") return (ETH, 18);
if (token == "usdc") return (USDC, 6);
if (token == "usdt" || token == "tether") return (USDT, 6);
if (token == "dai") return (DAI, 18);
if (token == "arb" || token == "arbitrum") return (ARB, 18);
if (token == "weth") return (WETH, 18);
if (token == "wbtc" || token == "btc" || token == "bitcoin") return (WBTC, 8);
if (token == "steth" || token == "wsteth" || token == "lido") return (WSTETH, 18);
if (token == "reth") return (RETH, 18);
}
/// @dev Checks and returns the canonical token string constant for a matched address.
function _returnTokenAliasConstants(address token)
internal
pure
virtual
returns (string memory _token, uint256 _decimals)
{
if (token == USDC) return ("USDC", 6);
if (token == USDT) return ("USDT", 6);
if (token == DAI) return ("DAI", 18);
if (token == ARB) return ("ARB", 18);
if (token == WETH) return ("WETH", 18);
if (token == WBTC) return ("WBTC", 8);
if (token == WSTETH) return ("WSTETH", 18);
if (token == RETH) return ("RETH", 18);
}
/// @dev Checks and returns popular pool pairs for WETH swaps.
function _returnPoolConstants(address token0, address token1)
internal
pure
virtual
returns (address pool)
{
if (token0 == WSTETH && token1 == WETH) return 0x35218a1cbaC5Bbc3E57fd9Bd38219D37571b3537;
if (token0 == WETH && token1 == RETH) return 0x09ba302A3f5ad2bF8853266e271b005A5b3716fe;
if (token0 == WETH && token1 == USDC) return 0xC6962004f452bE9203591991D15f6b388e09E8D0;
if (token0 == WETH && token1 == USDT) return 0x641C00A822e8b671738d32a431a4Fb6074E5c79d;
if (token0 == WETH && token1 == DAI) return 0xA961F0473dA4864C5eD28e00FcC53a3AAb056c1b;
if (token0 == WETH && token1 == ARB) return 0xC6F780497A95e246EB9449f5e4770916DCd6396A;
if (token0 == WBTC && token1 == WETH) return 0x2f5e87C9312fa29aed5c179E456625D79015299c;
}
/// ===================== COMMAND EXECUTION ===================== ///
/// @dev Executes a text command from an `intent` string.
function command(string calldata intent) public payable virtual {
bytes memory normalized = _lowercase(bytes(intent));
bytes32 action = _extraction(normalized);
if (action == "send" || action == "transfer" || action == "pay" || action == "grant") {
(bytes memory to, bytes memory amount, bytes memory token) = _extractSend(normalized);
send(string(to), string(amount), string(token));
} else if (
action == "swap" || action == "sell" || action == "exchange" || action == "stake"
) {
(
bytes memory amountIn,
bytes memory amountOutMin,
bytes memory tokenIn,
bytes memory tokenOut,
bytes memory receiver
) = _extractSwap(normalized);
swap(
string(amountIn),
string(amountOutMin),
string(tokenIn),
string(tokenOut),
string(receiver)
);
} else if (action == "lock" || action == "lockup") {
(
bytes memory to,
bytes memory amount,
bytes memory token,
bytes memory time,
bytes memory unit
) = _extractLock(normalized);
bytes32 id = lock(string(to), string(amount), string(token), string(time), string(unit));
assembly ("memory-safe") {
mstore(0x00, id)
return(0x00, 0x20)
}
} else if (action == "escrow") {
(
bytes memory to,
bytes memory amount,
bytes memory token,
bytes memory time,
bytes memory unit
) = _extractLock(normalized);
bytes32 id =
escrow(string(to), string(amount), string(token), string(time), string(unit));
assembly ("memory-safe") {
mstore(0x00, id)
return(0x00, 0x20)
}
} else if (action == "order") {
(
bytes memory amountIn,
bytes memory amountOut,
bytes memory tokenIn,
bytes memory tokenOut,
bytes memory receiver
) = _extractSwap(normalized);
bytes32 id = order(
string(tokenIn),
string(tokenOut),
string(amountIn),
string(amountOut),
string(receiver)
);
assembly ("memory-safe") {
mstore(0x00, id)
return(0x00, 0x20)
}
} else {
revert InvalidSyntax(); // Invalid command format.
}
}
/// @dev Executes batch of text commands from an `intents` string.
function command(string[] calldata intents) public payable virtual {
for (uint256 i; i != intents.length; ++i) {
command(intents[i]);
}
}
/// @dev Executes a `send` command from the parts of a matched intent string.
function send(string memory to, string memory amount, string memory token)
public
payable
virtual
{
address _token;
uint256 decimals;
if (bytes(token).length == 42) _token = _toAddress(bytes(token));
else (_token, decimals) = _returnTokenConstants(bytes32(bytes(token)));
if (_token == address(0)) _token = addresses[token];
(, address _to,) = whatIsTheAddressOf(to);
uint256 _amount =
_toUint(bytes(amount), decimals != 0 ? decimals : _token.readDecimals(), _token);
if (_token == ETH) {
require(msg.value == _amount);
_to.safeTransferETH(_amount);
} else {
_token.safeTransferFrom(msg.sender, _to, _amount);
}
}
/// @dev Executes a `lock` command from the parts of a matched intent string.
function lock(
string memory to,
string memory amount,
string memory token,
string memory time, /*'40'*/
string memory unit /*'days'*/
) public payable virtual returns (bytes32) {
return _escrow(bytes(to), bytes(amount), bytes(token), bytes(time), bytes(unit), true);
}
/// @dev Executes an `escrow` command from the parts of a matched intent string.
function escrow(
string memory to,
string memory amount,
string memory token,
string memory time, /*'40'*/
string memory unit /*'days'*/
) public payable virtual returns (bytes32) {
return _escrow(bytes(to), bytes(amount), bytes(token), bytes(time), bytes(unit), false);
}
/// @dev Handles either a `lock` or `escrow` command via Escrows protocol.
function _escrow(
bytes memory to,
bytes memory amount,
bytes memory token,
bytes memory time, /*'40'*/
bytes memory unit, /*'days'*/
bool lockup
) internal virtual returns (bytes32) {
address _token;
uint256 decimals;
if (bytes(token).length == 42) _token = _toAddress(bytes(token));
else (_token, decimals) = _returnTokenConstants(bytes32(token));
if (_token == address(0)) _token = addresses[string(token)];
(, address _to,) = whatIsTheAddressOf(string(to));
uint256 _amount = _toUint(amount, decimals != 0 ? decimals : _token.readDecimals(), _token);
uint256 _time = _simpleToUint256(time);
bytes32 _unit = bytes32(unit);
if (_unit == "minute" || _unit == "minutes") {
_time = _time * 1 minutes;
} else if (_unit == "day" || _unit == "days") {
_time = _time * 1 days;
} else if (_unit == "week" || _unit == "weeks") {
_time = _time * 1 weeks;
} else if (_unit == "month" || _unit == "months") {
_time = _time * 4 weeks;
} else if (_unit == "year" || _unit == "years") {
_time = _time * 52 weeks;
} else {
revert InvalidSyntax(); // Invalid `unit`.
}
if (_token == ETH) {
unchecked {
require(msg.value == _amount);
return IEscrows(ESCROWS).escrow{value: _amount}(
address(0),
lockup ? _to : msg.sender,
lockup ? msg.sender : _to,
CURIA,
_amount,
string(
abi.encodePacked(
"lock",
" ",
amount,
" ",
token,
" ",
"for",
" ",
to,
" ",
"for",
" ",
time,
" ",
unit
)
),
block.timestamp + _time
);
}
} else {
_token.safeTransferFrom(msg.sender, address(this), _amount);
_token.safeApprove(ESCROWS, _amount);
unchecked {
return IEscrows(ESCROWS).escrow(
_token,
lockup ? _to : msg.sender,
lockup ? msg.sender : _to,
CURIA,
_amount,
string(
abi.encodePacked(
"lock",
" ",
amount,
" ",
token,
" ",
"for",
" ",
to,
" ",
"for",
" ",
time,
" ",
unit
)
),
block.timestamp + _time
);
}
}
}
/// @dev Executes a `swap` command from the parts of a matched intent string.
function swap(
string memory amountIn,
string memory amountOutMin,
string memory tokenIn,
string memory tokenOut,
string memory receiver
) public payable virtual {
SwapInfo memory info;
uint256 decimalsIn;
uint256 decimalsOut;
if (bytes(tokenIn).length == 42) info.tokenIn = _toAddress(bytes(tokenIn));
else (info.tokenIn, decimalsIn) = _returnTokenConstants(bytes32(bytes(tokenIn)));
if (info.tokenIn == address(0)) info.tokenIn = addresses[tokenIn];
if (bytes(tokenOut).length == 42) info.tokenOut = _toAddress(bytes(tokenOut));
else (info.tokenOut, decimalsOut) = _returnTokenConstants(bytes32(bytes(tokenOut)));
if (info.tokenOut == address(0)) info.tokenOut = addresses[tokenOut];
uint256 minOut;
if (bytes(amountOutMin).length != 0) {
minOut = _toUint(
bytes(amountOutMin),
decimalsOut != 0 ? decimalsOut : info.tokenOut.readDecimals(),
info.tokenOut
);
}
bool exactOut = bytes(amountIn).length == 0;
info.amountIn = exactOut
? minOut
: _toUint(
bytes(amountIn),
decimalsIn != 0 ? decimalsIn : info.tokenIn.readDecimals(),
info.tokenIn
);
if (info.amountIn >= 1 << 255) revert Overflow();
info.ETHIn = info.tokenIn == ETH;
if (info.ETHIn) require(msg.value == info.amountIn);
if (info.ETHIn) info.tokenIn = WETH;
info.ETHOut = info.tokenOut == ETH;
if (info.ETHOut) info.tokenOut = WETH;
address _receiver;
if (bytes(receiver).length == 0) _receiver = msg.sender;
else (, _receiver,) = whatIsTheAddressOf(receiver);
(address pool, bool zeroForOne) = _computePoolAddress(info.tokenIn, info.tokenOut);
(int256 amount0, int256 amount1) = ISwapRouter(pool).swap(
!info.ETHOut ? _receiver : address(this),
zeroForOne,
!exactOut ? int256(info.amountIn) : -int256(info.amountIn),
zeroForOne ? MIN_SQRT_RATIO_PLUS_ONE : MAX_SQRT_RATIO_MINUS_ONE,
abi.encodePacked(
info.ETHIn, info.ETHOut, msg.sender, info.tokenIn, info.tokenOut, _receiver
)
);
if (minOut != 0) {
if (uint256(-(zeroForOne ? amount1 : amount0)) < minOut) revert InsufficientSwap();
}
}
/// @dev Fallback `uniswapV3SwapCallback`.
/// If ETH is swapped, WETH is forwarded.
fallback() external payable virtual {
int256 amount0Delta;
int256 amount1Delta;
bool ETHIn;
bool ETHOut;
address payer;
address tokenIn;
address tokenOut;
address receiver;
assembly ("memory-safe") {
amount0Delta := calldataload(0x4)
amount1Delta := calldataload(0x24)
ETHIn := byte(0, calldataload(0x84))
ETHOut := byte(0, calldataload(add(0x84, 1)))
payer := shr(96, calldataload(add(0x84, 2)))
tokenIn := shr(96, calldataload(add(0x84, 22)))
tokenOut := shr(96, calldataload(add(0x84, 42)))
receiver := shr(96, calldataload(add(0x84, 62)))
}
if (amount0Delta <= 0 && amount1Delta <= 0) revert InvalidSwap();
(address pool, bool zeroForOne) = _computePoolAddress(tokenIn, tokenOut);
assembly ("memory-safe") {
if iszero(eq(caller(), pool)) { revert(codesize(), codesize()) }
}
if (ETHIn) {
_wrapETH(uint256(zeroForOne ? amount0Delta : amount1Delta));
} else {
tokenIn.safeTransferFrom(payer, pool, uint256(zeroForOne ? amount0Delta : amount1Delta));
}
if (ETHOut) {
uint256 amount = uint256(-(zeroForOne ? amount1Delta : amount0Delta));
_unwrapETH(amount);
receiver.safeTransferETH(amount);
}
}
/// @dev Computes the create2 address for given token pair.
/// note: This process checks all available pools for price.
function _computePoolAddress(address tokenA, address tokenB)
internal
view
virtual
returns (address pool, bool zeroForOne)
{
if (tokenA < tokenB) zeroForOne = true;
else (tokenA, tokenB) = (tokenB, tokenA);
pool = _returnPoolConstants(tokenA, tokenB);
if (pool == address(0)) {
pool = pairs[tokenA][tokenB];
if (pool == address(0)) {
address pool100 = _computePairHash(tokenA, tokenB, 100); // Lowest fee.
address pool500 = _computePairHash(tokenA, tokenB, 500); // Lower fee.
address pool3000 = _computePairHash(tokenA, tokenB, 3000); // Mid fee.
address pool10000 = _computePairHash(tokenA, tokenB, 10000); // Hi fee.
SwapLiq memory topPool;
uint256 liq;
if (pool100.code.length != 0) {
liq = _balanceOf(tokenA, pool100);
topPool = SwapLiq(pool100, liq);
}
if (pool500.code.length != 0) {
liq = _balanceOf(tokenA, pool500);
if (liq > topPool.liq) {
topPool = SwapLiq(pool500, liq);
}
}
if (pool3000.code.length != 0) {
liq = _balanceOf(tokenA, pool3000);
if (liq > topPool.liq) {
topPool = SwapLiq(pool3000, liq);
}
}
if (pool10000.code.length != 0) {
liq = _balanceOf(tokenA, pool10000);
if (liq > topPool.liq) {
topPool = SwapLiq(pool10000, liq);
}
}
pool = topPool.pool; // Return top pool.
}
}
}
/// @dev Computes the create2 deployment hash for a given token pair.
function _computePairHash(address token0, address token1, uint24 fee)
internal
pure
virtual
returns (address pool)
{
bytes32 salt = _hash(token0, token1, fee);
assembly ("memory-safe") {
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, UNISWAP_V3_POOL_INIT_CODE_HASH)
mstore(0x01, shl(96, UNISWAP_V3_FACTORY))
mstore(0x15, salt)
pool := keccak256(0x00, 0x55)
mstore(0x35, 0) // Restore overwritten.
}
}
/// @dev Returns `keccak256(abi.encode(value0, value1, value2))`.
function _hash(address value0, address value1, uint24 value2)
internal
pure
virtual
returns (bytes32 result)
{
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, value0)
mstore(add(m, 0x20), value1)
mstore(add(m, 0x40), value2)
result := keccak256(m, 0x60)
}
}
/// @dev Wraps an `amount` of ETH to WETH and funds pool caller for swap.
function _wrapETH(uint256 amount) internal virtual {
assembly ("memory-safe") {
pop(call(gas(), WETH, amount, codesize(), 0x00, codesize(), 0x00))
mstore(0x14, caller()) // Store the `pool` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
pop(call(gas(), WETH, 0, 0x10, 0x44, codesize(), 0x00))
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Unwraps an `amount` of ETH from WETH for return.
function _unwrapETH(uint256 amount) internal virtual {
assembly ("memory-safe") {
mstore(0x00, 0x2e1a7d4d) // `withdraw(uint256)`.
mstore(0x20, amount) // Store the `amount` argument.
pop(call(gas(), WETH, 0, 0x1c, 0x24, codesize(), 0x00))
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
function _balanceOf(address token, address account)
internal
view
virtual
returns (uint256 amount)
{
assembly ("memory-safe") {
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
mstore(0x14, account) // Store the `account` argument.
pop(staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20))
amount := mload(0x20)
}
}
/// @dev ETH receiver fallback.
/// Only canonical WETH can call.
receive() external payable virtual {
assembly ("memory-safe") {
if iszero(eq(caller(), WETH)) { revert(codesize(), codesize()) }
}
}
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
assembly ("memory-safe") {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
assembly ("memory-safe") {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Executes an `order` command from the parts of a matched intent string.
function order(
string memory tokenIn,
string memory tokenOut,
string memory amountIn,
string memory amountOut,
string memory receiver
) public payable nonReentrant returns (bytes32 hash) {
Order memory o;
uint256 decimalsIn;
uint256 decimalsOut;
if (bytes(tokenIn).length == 42) o.tokenIn = _toAddress(bytes(tokenIn));
else (o.tokenIn, decimalsIn) = _returnTokenConstants(bytes32(bytes(tokenIn)));
if (o.tokenIn == address(0)) o.tokenIn = addresses[string(tokenIn)];
if (bytes(tokenOut).length == 42) o.tokenOut = _toAddress(bytes(tokenOut));
else (o.tokenOut, decimalsOut) = _returnTokenConstants(bytes32(bytes(tokenOut)));
if (o.tokenOut == address(0)) o.tokenOut = addresses[string(bytes(tokenOut))];
o.amountIn = _toUint(
bytes(amountIn), decimalsIn != 0 ? decimalsIn : o.tokenIn.readDecimals(), o.tokenIn
);
o.amountOut = _toUint(
bytes(amountOut), decimalsOut != 0 ? decimalsOut : o.tokenOut.readDecimals(), o.tokenOut
);
if (o.tokenIn == ETH) require(msg.value == o.amountIn);
unchecked {
o.maker = msg.sender;
address _receiver;
if (bytes(receiver).length == 0) _receiver = msg.sender;
else (, _receiver,) = whatIsTheAddressOf(receiver);
o.receiver = _receiver;
o.nonce = uint48(block.timestamp);
o.expiry = uint48(block.timestamp + 1 weeks);
orders[hash = keccak256(abi.encode(o))] = o;
orderHashes.push(hash);
}
}
/// @dev Cancels a standing order by the `maker`.
function cancelOrder(bytes32 hash) public nonReentrant {
Order memory o = orders[hash];
delete orders[hash];
if (msg.sender != o.maker) revert Unauthorized();
if (o.tokenIn == ETH) msg.sender.safeTransferETH(o.amountIn);
}
/// @dev Executes a standing order for the `receiver`.
function executeOrder(bytes32 hash) public payable nonReentrant {
Order memory o = orders[hash];
delete orders[hash];
if (block.timestamp > o.expiry) revert OrderExpired();
if (o.tokenIn == ETH) msg.sender.safeTransferETH(o.amountIn);
else o.tokenIn.safeTransferFrom(o.maker, msg.sender, o.amountIn);
if (o.tokenOut == ETH) {
require(msg.value == o.amountOut);
o.receiver.safeTransferETH(msg.value);
} else {
o.tokenOut.safeTransferFrom(msg.sender, o.receiver, o.amountOut);
}
}
/// ==================== COMMAND TRANSLATION ==================== ///
/// @dev Translates an `intent` from raw `command()` calldata.
function translateCommand(bytes calldata callData)
public
pure
virtual
returns (string memory intent)
{
return string(callData[4:]);
}
/// @dev Translates an `intent` for send action from the solution `callData` of standard `execute()`.
/// note: The function selector technically doesn't need to be `execute()` but params should match.
function translateExecute(bytes calldata callData)
public
view
virtual
returns (string memory intent)
{
unchecked {
(address target, uint256 value) = abi.decode(callData[4:68], (address, uint256));
if (value != 0) {
return string(
abi.encodePacked(
"send ",
_convertWeiToString(value, 18),
" ETH to 0x",
_toAsciiString(target)
)
);
}
if (
bytes4(callData[132:136]) != IToken.transfer.selector
&& bytes4(callData[132:136]) != IToken.approve.selector
) revert InvalidSelector();
bool transfer = bytes4(callData[132:136]) == IToken.transfer.selector;
(string memory token, uint256 decimals) = _returnTokenAliasConstants(target);
if (bytes(token).length == 0) token = names[target];
if (decimals == 0) decimals = target.readDecimals(); // Sanity check.