@keep-network/tbtc-v2 0.1.1-dev.2 → 0.1.1-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,374 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ // ██████████████ ▐████▌ ██████████████
4
+ // ██████████████ ▐████▌ ██████████████
5
+ // ▐████▌ ▐████▌
6
+ // ▐████▌ ▐████▌
7
+ // ██████████████ ▐████▌ ██████████████
8
+ // ██████████████ ▐████▌ ██████████████
9
+ // ▐████▌ ▐████▌
10
+ // ▐████▌ ▐████▌
11
+ // ▐████▌ ▐████▌
12
+ // ▐████▌ ▐████▌
13
+ // ▐████▌ ▐████▌
14
+ // ▐████▌ ▐████▌
15
+
16
+ pragma solidity 0.8.4;
17
+
18
+ import "@openzeppelin/contracts/access/Ownable.sol";
19
+
20
+ import "../vault/IVault.sol";
21
+
22
+ /// @title Bitcoin Bank
23
+ /// @notice Bank is a central component tracking Bitcoin balances. Balances can
24
+ /// be transferred between holders and holders can approve their
25
+ /// balances to be spent by others. Balances in the Bank are updated for
26
+ /// depositors who deposit their Bitcoin into the Bridge and only the
27
+ /// Bridge can increase balances.
28
+ /// @dev Bank is a governable contract and the Governance can upgrade the Bridge
29
+ /// address.
30
+ contract Bank is Ownable {
31
+ address public bridge;
32
+
33
+ /// @notice The balance of a given account in the Bank. Zero by default.
34
+ mapping(address => uint256) public balanceOf;
35
+
36
+ /// @notice The remaining amount of balance a spender will be
37
+ /// allowed to transfer on behalf of an owner using
38
+ /// `transferBalanceFrom`. Zero by default.
39
+ mapping(address => mapping(address => uint256)) public allowance;
40
+
41
+ /// @notice Returns the current nonce for EIP2612 permission for the
42
+ /// provided balance owner for a replay protection. Used to
43
+ /// construct EIP2612 signature provided to `permit` function.
44
+ mapping(address => uint256) public nonce;
45
+
46
+ uint256 public immutable cachedChainId;
47
+ bytes32 public immutable cachedDomainSeparator;
48
+
49
+ /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612
50
+ /// signature provided to `permit` function.
51
+ bytes32 public constant PERMIT_TYPEHASH =
52
+ keccak256(
53
+ "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
54
+ );
55
+
56
+ event BalanceTransferred(
57
+ address indexed from,
58
+ address indexed to,
59
+ uint256 amount
60
+ );
61
+
62
+ event BalanceApproved(
63
+ address indexed owner,
64
+ address indexed spender,
65
+ uint256 amount
66
+ );
67
+
68
+ event BalanceIncreased(address indexed owner, uint256 amount);
69
+
70
+ event BalanceDecreased(address indexed owner, uint256 amount);
71
+
72
+ event BridgeUpdated(address newBridge);
73
+
74
+ modifier onlyBridge() {
75
+ require(msg.sender == address(bridge), "Caller is not the bridge");
76
+ _;
77
+ }
78
+
79
+ constructor() {
80
+ cachedChainId = block.chainid;
81
+ cachedDomainSeparator = buildDomainSeparator();
82
+ }
83
+
84
+ /// @notice Allows the Governance to upgrade the Bridge address.
85
+ /// @dev The function does not implement any governance delay and does not
86
+ /// check the status of the Bridge. The Governance implementation needs
87
+ /// to ensure all requirements for the upgrade are satisfied before
88
+ /// executing this function.
89
+ function updateBridge(address _bridge) external onlyOwner {
90
+ require(_bridge != address(0), "Bridge address must not be 0x0");
91
+ bridge = _bridge;
92
+ emit BridgeUpdated(_bridge);
93
+ }
94
+
95
+ /// @notice Moves the given `amount` of balance from the caller to
96
+ /// `recipient`.
97
+ /// @dev Requirements:
98
+ /// - `recipient` cannot be the zero address,
99
+ /// - the caller must have a balance of at least `amount`.
100
+ function transferBalance(address recipient, uint256 amount) external {
101
+ _transferBalance(msg.sender, recipient, amount);
102
+ }
103
+
104
+ /// @notice Sets `amount` as the allowance of `spender` over the caller's
105
+ /// balance.
106
+ /// @dev If the `amount` is set to `type(uint256).max` then
107
+ /// `transferBalanceFrom` will not reduce an allowance.
108
+ /// Beware that changing an allowance with this function brings the
109
+ /// risk that someone may use both the old and the new allowance by
110
+ /// unfortunate transaction ordering. Please use
111
+ /// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to
112
+ /// eliminate the risk.
113
+ function approveBalance(address spender, uint256 amount) external {
114
+ _approveBalance(msg.sender, spender, amount);
115
+ }
116
+
117
+ /// @notice Atomically increases the balance allowance granted to `spender`
118
+ /// by the caller by the given `addedValue`.
119
+ function increaseBalanceAllowance(address spender, uint256 addedValue)
120
+ external
121
+ {
122
+ _approveBalance(
123
+ msg.sender,
124
+ spender,
125
+ allowance[msg.sender][spender] + addedValue
126
+ );
127
+ }
128
+
129
+ /// @notice Atomically decreases the balance allowance granted to `spender`
130
+ /// by the caller by the given `subtractedValue`.
131
+ function decreaseBalanceAllowance(address spender, uint256 subtractedValue)
132
+ external
133
+ {
134
+ uint256 currentAllowance = allowance[msg.sender][spender];
135
+ require(
136
+ currentAllowance >= subtractedValue,
137
+ "Can not decrease balance allowance below zero"
138
+ );
139
+ unchecked {
140
+ _approveBalance(
141
+ msg.sender,
142
+ spender,
143
+ currentAllowance - subtractedValue
144
+ );
145
+ }
146
+ }
147
+
148
+ /// @notice Moves `amount` of balance from `spender` to `recipient` using the
149
+ /// allowance mechanism. `amount` is then deducted from the caller's
150
+ /// allowance unless the allowance was made for `type(uint256).max`.
151
+ /// @dev Requirements:
152
+ /// - `recipient` cannot be the zero address,
153
+ /// - `spender` must have a balance of at least `amount`,
154
+ /// - the caller must have allowance for `spender`'s balance of at
155
+ /// least `amount`.
156
+ function transferBalanceFrom(
157
+ address spender,
158
+ address recipient,
159
+ uint256 amount
160
+ ) external {
161
+ uint256 currentAllowance = allowance[spender][msg.sender];
162
+ if (currentAllowance != type(uint256).max) {
163
+ require(
164
+ currentAllowance >= amount,
165
+ "Transfer amount exceeds allowance"
166
+ );
167
+ unchecked {
168
+ _approveBalance(spender, msg.sender, currentAllowance - amount);
169
+ }
170
+ }
171
+ _transferBalance(spender, recipient, amount);
172
+ }
173
+
174
+ /// @notice EIP2612 approval made with secp256k1 signature.
175
+ /// Users can authorize a transfer of their balance with a signature
176
+ /// conforming EIP712 standard, rather than an on-chain transaction
177
+ /// from their address. Anyone can submit this signature on the
178
+ /// user's behalf by calling the permit function, paying gas fees,
179
+ /// and possibly performing other actions in the same transaction.
180
+ /// @dev The deadline argument can be set to `type(uint256).max to create
181
+ /// permits that effectively never expire. If the `amount` is set
182
+ /// to `type(uint256).max` then `transferBalanceFrom` will not
183
+ /// reduce an allowance. Beware that changing an allowance with this
184
+ /// function brings the risk that someone may use both the old and the
185
+ /// new allowance by unfortunate transaction ordering. Please use
186
+ /// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to
187
+ /// eliminate the risk.
188
+ function permit(
189
+ address owner,
190
+ address spender,
191
+ uint256 amount,
192
+ uint256 deadline,
193
+ uint8 v,
194
+ bytes32 r,
195
+ bytes32 s
196
+ ) external {
197
+ /* solhint-disable-next-line not-rely-on-time */
198
+ require(deadline >= block.timestamp, "Permission expired");
199
+
200
+ // Validate `s` and `v` values for a malleability concern described in EIP2.
201
+ // Only signatures with `s` value in the lower half of the secp256k1
202
+ // curve's order and `v` value of 27 or 28 are considered valid.
203
+ require(
204
+ uint256(s) <=
205
+ 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
206
+ "Invalid signature 's' value"
207
+ );
208
+ require(v == 27 || v == 28, "Invalid signature 'v' value");
209
+
210
+ bytes32 digest =
211
+ keccak256(
212
+ abi.encodePacked(
213
+ "\x19\x01",
214
+ DOMAIN_SEPARATOR(),
215
+ keccak256(
216
+ abi.encode(
217
+ PERMIT_TYPEHASH,
218
+ owner,
219
+ spender,
220
+ amount,
221
+ nonce[owner]++,
222
+ deadline
223
+ )
224
+ )
225
+ )
226
+ );
227
+ address recoveredAddress = ecrecover(digest, v, r, s);
228
+ require(
229
+ recoveredAddress != address(0) && recoveredAddress == owner,
230
+ "Invalid signature"
231
+ );
232
+ _approveBalance(owner, spender, amount);
233
+ }
234
+
235
+ /// @notice Increases balances of the provided `recipients` by the provided
236
+ /// `amounts`. Can only be called by the Bridge.
237
+ /// @dev Requirements:
238
+ /// - length of `recipients` and `amounts` must be the same.
239
+ function increaseBalances(
240
+ address[] calldata recipients,
241
+ uint256[] calldata amounts
242
+ ) external onlyBridge {
243
+ require(
244
+ recipients.length == amounts.length,
245
+ "Arrays must have the same length"
246
+ );
247
+ for (uint256 i = 0; i < recipients.length; i++) {
248
+ _increaseBalance(recipients[i], amounts[i]);
249
+ }
250
+ }
251
+
252
+ /// @notice Increases balance of the provided `recipient` by the provided
253
+ /// `amount`. Can only be called by the Bridge.
254
+ function increaseBalance(address recipient, uint256 amount)
255
+ external
256
+ onlyBridge
257
+ {
258
+ _increaseBalance(recipient, amount);
259
+ }
260
+
261
+ /// @notice Increases the given smart contract `vault`'s balance and
262
+ /// notifies the `vault` contract. Called by the Bridge after
263
+ /// the deposits routed by depositors to that `vault` have been
264
+ /// swept by the Bridge. This way, the depositor does not have to
265
+ /// issue a separate transaction to the `vault` contract.
266
+ /// Can be called only by the Bridge.
267
+ /// @dev Requirements:
268
+ /// - `vault` must implement `IVault` interface,
269
+ /// - length of `depositors` and `depositedAmounts` must be the same.
270
+ /// @param vault Address of `IVault` recipient contract
271
+ /// @param depositors Addresses of depositors whose deposits have been swept
272
+ /// @param depositedAmounts Amounts deposited by individual depositors and
273
+ /// swept. The `vault`'s balance in the Bank will be increased by the
274
+ /// sum of all elements in this array.
275
+ function increaseBalanceAndCall(
276
+ address vault,
277
+ address[] calldata depositors,
278
+ uint256[] calldata depositedAmounts
279
+ ) external onlyBridge {
280
+ require(
281
+ depositors.length == depositedAmounts.length,
282
+ "Arrays must have the same length"
283
+ );
284
+ uint256 totalAmount = 0;
285
+ for (uint256 i = 0; i < depositedAmounts.length; i++) {
286
+ totalAmount += depositedAmounts[i];
287
+ }
288
+ _increaseBalance(vault, totalAmount);
289
+ IVault(vault).onBalanceIncreased(depositors, depositedAmounts);
290
+ }
291
+
292
+ /// @notice Decreases caller's balance by the provided `amount`. There is no
293
+ /// way to restore the balance so do not call this function unless
294
+ /// you really know what you are doing!
295
+ function decreaseBalance(uint256 amount) external {
296
+ balanceOf[msg.sender] -= amount;
297
+ emit BalanceDecreased(msg.sender, amount);
298
+ }
299
+
300
+ /// @notice Returns hash of EIP712 Domain struct with `TBTC Bank` as
301
+ /// a signing domain and Bank contract as a verifying contract.
302
+ /// Used to construct EIP2612 signature provided to `permit`
303
+ /// function.
304
+ /* solhint-disable-next-line func-name-mixedcase */
305
+ function DOMAIN_SEPARATOR() public view returns (bytes32) {
306
+ // As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the
307
+ // chainId and is defined at contract deployment instead of
308
+ // reconstructed for every signature, there is a risk of possible replay
309
+ // attacks between chains in the event of a future chain split.
310
+ // To address this issue, we check the cached chain ID against the
311
+ // current one and in case they are different, we build domain separator
312
+ // from scratch.
313
+ if (block.chainid == cachedChainId) {
314
+ return cachedDomainSeparator;
315
+ } else {
316
+ return buildDomainSeparator();
317
+ }
318
+ }
319
+
320
+ function _increaseBalance(address recipient, uint256 amount) internal {
321
+ require(
322
+ recipient != address(this),
323
+ "Can not increase balance for Bank"
324
+ );
325
+ balanceOf[recipient] += amount;
326
+ emit BalanceIncreased(recipient, amount);
327
+ }
328
+
329
+ function _transferBalance(
330
+ address spender,
331
+ address recipient,
332
+ uint256 amount
333
+ ) private {
334
+ require(
335
+ recipient != address(0),
336
+ "Can not transfer to the zero address"
337
+ );
338
+ require(
339
+ recipient != address(this),
340
+ "Can not transfer to the Bank address"
341
+ );
342
+
343
+ uint256 spenderBalance = balanceOf[spender];
344
+ require(spenderBalance >= amount, "Transfer amount exceeds balance");
345
+ unchecked {balanceOf[spender] = spenderBalance - amount;}
346
+ balanceOf[recipient] += amount;
347
+ emit BalanceTransferred(spender, recipient, amount);
348
+ }
349
+
350
+ function _approveBalance(
351
+ address owner,
352
+ address spender,
353
+ uint256 amount
354
+ ) private {
355
+ require(spender != address(0), "Can not approve to the zero address");
356
+ allowance[owner][spender] = amount;
357
+ emit BalanceApproved(owner, spender, amount);
358
+ }
359
+
360
+ function buildDomainSeparator() private view returns (bytes32) {
361
+ return
362
+ keccak256(
363
+ abi.encode(
364
+ keccak256(
365
+ "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
366
+ ),
367
+ keccak256(bytes("TBTC Bank")),
368
+ keccak256(bytes("1")),
369
+ block.chainid,
370
+ address(this)
371
+ )
372
+ );
373
+ }
374
+ }