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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// This contract is part of Zellic’s smart contract dataset, which is a collection of publicly available contract code gathered as of March 2023.

# @version 0.2.16
"""

@title Liquidity Gauge v4

@author StakeDAO Protocol

@license MIT

"""

# Original idea and credit:
# Curve Finance's veCRV
# https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/gauges/LiquidityGaugeV4.vy
# Mostly forked from Curve, except that now there is no direct link between the gauge controller
# and the gauges. In this implementation, SDT rewards are like any other token rewards.

from vyper.interfaces import ERC20

interface VotingEscrow:
    def user_point_epoch(addr: address) -> uint256: view
    def user_point_history__ts(addr: address, epoch: uint256) -> uint256: view

interface VotingEscrowBoost:
    def adjusted_balance_of(_account: address) -> uint256: view

interface PoolRegistry: 
    def vaultMap(_poolId: uint256, _owner : address) -> address: view

event Deposit:
    provider: indexed(address)
    value: uint256

event Withdraw:
    provider: indexed(address)
    value: uint256

event UpdateLiquidityLimit:
    user: address
    original_balance: uint256
    original_supply: uint256
    working_balance: uint256
    working_supply: uint256

event CommitOwnership:
    admin: address

event ApplyOwnership:
    admin: address

event RewardDataUpdate:
    _token: indexed(address)
    _amount: uint256

struct Reward:
    token: address
    distributor: address
    period_finish: uint256
    rate: uint256
    last_update: uint256
    integral: uint256


MAX_REWARDS: constant(uint256) = 8
TOKENLESS_PRODUCTION: constant(uint256) = 40
WEEK: constant(uint256) = 604800

SDT: public(address)
voting_escrow: public(address)
veBoost_proxy: public(address)

balanceOf: public(HashMap[address, uint256])
totalSupply: public(uint256)

working_balances: public(HashMap[address, uint256])
working_supply: public(uint256)

integrate_checkpoint_of: public(HashMap[address, uint256])

# For tracking external rewards
reward_count: public(uint256)
reward_tokens: public(address[MAX_REWARDS])

reward_data: public(HashMap[address, Reward])

# claimant -> default reward receiver
rewards_receiver: public(HashMap[address, address])

# reward token -> claiming address -> integral
reward_integral_for: public(HashMap[address, HashMap[address, uint256]])

# user -> [uint128 claimable amount][uint128 claimed amount]
claim_data: HashMap[address, HashMap[address, uint256]]

admin: public(address)
future_admin: public(address)
claimer: public(address)
pool_registry: public(address)

initialized: public(bool)

pid: public(uint256)

@external
def __init__():
    """

    @notice Contract constructor

    @dev The contract has an initializer to prevent the take over of the implementation

    """
    assert self.initialized == False #dev: contract is already initialized
    self.initialized = True

@external
def initialize(_admin: address, _SDT: address, _voting_escrow: address, _veBoost_proxy: address, _distributor: address, _pid: uint256, _pool_registry: address):
    """

    @notice Contract initializer

    @param _admin Admin who can kill the gauge

    @param _SDT Address of the SDT token

    @param _voting_escrow Address of the veSDT contract

    @param _veBoost_proxy Address of the proxy contract used to query veSDT balances and taking into account potential delegations

    @param _distributor Address of the contract responsible for distributing SDT tokens to this gauge

    @param _pid pool id corresponding to this gauge

    @param _pool_registry Address of the pool registry contract

    """
    assert self.initialized == False #dev: contract is already initialized
    self.initialized = True

    assert _admin != ZERO_ADDRESS
    assert _SDT != ZERO_ADDRESS
    assert _voting_escrow != ZERO_ADDRESS
    assert _veBoost_proxy != ZERO_ADDRESS
    assert _distributor != ZERO_ADDRESS

    self.admin = _admin
    self.SDT = _SDT
    self.voting_escrow = _voting_escrow
    self.veBoost_proxy = _veBoost_proxy
    self.pid = _pid
    self.pool_registry = _pool_registry

    # add in all liquidityGauge the SDT reward - the distribution could be null though
    self.reward_data[_SDT].distributor = _distributor
    self.reward_tokens[0] = _SDT
    self.reward_count = 1
    

@internal
def _update_liquidity_limit(addr: address, l: uint256, L: uint256):
    """

    @notice Calculate limits which depend on the amount of SDT token per-user.

            Effectively it calculates working balances to apply amplification

            of SDT production by SDT

    @param addr User address

    @param l User's amount of liquidity (LP tokens)

    @param L Total amount of liquidity (LP tokens)

    """
    # To be called after totalSupply is updated
    voting_balance: uint256 = VotingEscrowBoost(self.veBoost_proxy).adjusted_balance_of(addr)
    voting_total: uint256 = ERC20(self.voting_escrow).totalSupply()

    lim: uint256 = l * TOKENLESS_PRODUCTION / 100
    if voting_total > 0:
        lim += L * voting_balance / voting_total * (100 - TOKENLESS_PRODUCTION) / 100

    lim = min(l, lim)
    old_bal: uint256 = self.working_balances[addr]
    self.working_balances[addr] = lim
    _working_supply: uint256 = self.working_supply + lim - old_bal
    self.working_supply = _working_supply

    log UpdateLiquidityLimit(addr, l, L, lim, _working_supply)


@internal
def _checkpoint_reward(_user: address, token: address, _total_supply: uint256, _user_balance: uint256, _claim: bool, receiver: address):
    """

    @notice Claim pending rewards and checkpoint rewards for a user

    @param _user Account to checkpoint reward for

    @param token Token to checkpoint reward for

    @param _total_supply Amount total deposited in the contract

    @param _user_balance Amount total deposited in the contract for _user

    @param _claim Bool to claim (or not) reward during the checkpoint

    @param receiver Address to transfer the claimed reward

    """
    total_supply: uint256 = _total_supply
    user_balance: uint256 = _user_balance
    if token == self.SDT : 
        total_supply = self.working_supply
        user_balance = self.working_balances[_user]

    integral: uint256 = self.reward_data[token].integral
    last_update: uint256 = min(block.timestamp, self.reward_data[token].period_finish)
    duration: uint256 = last_update - self.reward_data[token].last_update
    if duration != 0:
        self.reward_data[token].last_update = last_update
        if total_supply != 0:
            integral += duration * self.reward_data[token].rate * 10**18 / total_supply
            self.reward_data[token].integral = integral

    if _user != ZERO_ADDRESS:
        integral_for: uint256 = self.reward_integral_for[token][_user]
        new_claimable: uint256 = 0

        if integral_for < integral:
            self.reward_integral_for[token][_user] = integral
            new_claimable = user_balance * (integral - integral_for) / 10**18

        claim_data: uint256 = self.claim_data[_user][token]
        total_claimable: uint256 = shift(claim_data, -128) + new_claimable
        if total_claimable > 0:
            total_claimed: uint256 = claim_data % 2**128
            if _claim:
                response: Bytes[32] = raw_call(
                    token,
                    concat(
                        method_id("transfer(address,uint256)"),
                        convert(receiver, bytes32),
                        convert(total_claimable, bytes32),
                    ),
                    max_outsize=32,
                )
                if len(response) != 0:
                    assert convert(response, bool)
                self.claim_data[_user][token] = total_claimed + total_claimable
            elif new_claimable > 0:
                self.claim_data[_user][token] = total_claimed + shift(total_claimable, 128)
    
    if token == self.SDT : 
        self.integrate_checkpoint_of[_user] = block.timestamp
                
@internal
def _checkpoint_rewards(_user: address, _total_supply: uint256, _claim: bool, _receiver: address, _only_checkpoint:bool = False):
    """

    @notice Claim pending rewards and checkpoint rewards for a user

    @param _user Account to checkpoint reward for

    @param _total_supply Amount total deposited in the contract

    @param _user_balance Amount total deposited in the contract for _user

    @param _claim Bool to claim (or not) reward during the checkpoint

    @param _receiver Address to transfer the claimed reward

    @param _only_checkpoint Bool to call only checkpoint reward

    """

    receiver: address = _receiver
    user_balance: uint256 = 0
    if _user != ZERO_ADDRESS:
        user_balance = self.balanceOf[_user]
        if _claim and _receiver == ZERO_ADDRESS:
            # if receiver is not explicitly declared, check if a default receiver is set
            receiver = self.rewards_receiver[_user]
            if receiver == ZERO_ADDRESS:
                # if no default receiver is set, direct claims to the user
                receiver = _user

    if _only_checkpoint:
        self._checkpoint_reward(_user, self.SDT, _total_supply, user_balance, False, receiver)
    else:
        reward_count: uint256 = self.reward_count
        for i in range(MAX_REWARDS):
            if i == reward_count:
                break
            token: address = self.reward_tokens[i]
            self._checkpoint_reward(_user, token, _total_supply, user_balance, _claim, receiver)

@external
def user_checkpoint(addr: address) -> bool:
    """

    @notice Record a checkpoint for `addr`

    @param addr User address

    @return bool success

    """
    assert msg.sender == addr  # dev: unauthorized
    total_supply: uint256 = self.totalSupply
    self._checkpoint_rewards(addr, total_supply, False, ZERO_ADDRESS, True)
    self._update_liquidity_limit(addr, self.balanceOf[addr], total_supply)
    return True

@view
@external
def claimed_reward(_addr: address, _token: address) -> uint256:
    """

    @notice Get the number of already-claimed reward tokens for a user

    @param _addr Account to get reward amount for

    @param _token Token to get reward amount for

    @return uint256 Total amount of `_token` already claimed by `_addr`

    """
    return self.claim_data[_addr][_token] % 2**128


@view
@external
def claimable_reward(_user: address, _reward_token: address) -> uint256:
    """

    @notice Get the number of claimable reward tokens for a user

    @param _user Account to get reward amount for

    @param _reward_token Token to get reward amount for

    @return uint256 Claimable reward token amount

    """
    integral: uint256 = self.reward_data[_reward_token].integral
    total_supply: uint256 = self.totalSupply
    user_balance: uint256 = self.balanceOf[_user]
    if _reward_token == self.SDT: 
        total_supply = self.working_supply
        user_balance = self.working_balances[_user]
        
    if total_supply != 0:
        last_update: uint256 = min(block.timestamp, self.reward_data[_reward_token].period_finish)
        duration: uint256 = last_update - self.reward_data[_reward_token].last_update
        integral += (duration * self.reward_data[_reward_token].rate * 10**18 / total_supply)

    integral_for: uint256 = self.reward_integral_for[_reward_token][_user]
    new_claimable: uint256 = user_balance * (integral - integral_for) / 10**18

    return shift(self.claim_data[_user][_reward_token], -128) + new_claimable


@external
def set_rewards_receiver(_receiver: address):
    """

    @notice Set the default reward receiver for the caller.

    @dev When set to ZERO_ADDRESS, rewards are sent to the caller

    @param _receiver Receiver address for any rewards claimed via `claim_rewards`

    """
    self.rewards_receiver[msg.sender] = _receiver

@external
@nonreentrant('lock')
def claim_rewards(_addr: address = msg.sender, _receiver: address = ZERO_ADDRESS):
    """

    @notice Claim available reward tokens for `_addr`

    @param _addr Address to claim for

    @param _receiver Address to transfer rewards to - if set to

                     ZERO_ADDRESS, uses the default reward receiver

                     for the caller

    """
    if _receiver != ZERO_ADDRESS:
        assert _addr == msg.sender  # dev: cannot redirect when claiming for another user
    self._checkpoint_rewards(_addr, self.totalSupply, True, _receiver)

@external
@nonreentrant('lock')
def claim_rewards_for(_addr: address, _receiver: address):
    """

    @notice Claim available reward tokens for `_addr`

    @param _addr Address to claim for

    @param _receiver Address to transfer rewards to - if set to

                     ZERO_ADDRESS, uses the default reward receiver

                     for the caller

    """
    assert self.claimer == msg.sender  # dev: only the claim contract can claim for other 
    if _receiver != _addr:
        assert _receiver == self.claimer # dev: if the receiver is not the user it needs to be the claimer
    self._checkpoint_rewards(_addr, self.totalSupply, True, _receiver)


@external
def kick(addr: address):
    """

    @notice Kick `addr` for abusing their boost

    @dev Only if either they had another voting event, or their voting escrow lock expired

    @param addr Address to kick

    """
    t_last: uint256 = self.integrate_checkpoint_of[addr]
    t_ve: uint256 = VotingEscrow(self.voting_escrow).user_point_history__ts(
        addr, VotingEscrow(self.voting_escrow).user_point_epoch(addr)
    )
    _balance: uint256 = self.balanceOf[addr]

    assert ERC20(self.voting_escrow).balanceOf(addr) == 0 or t_ve > t_last # dev: kick not allowed
    assert self.working_balances[addr] > _balance * TOKENLESS_PRODUCTION / 100  # dev: kick not needed

    total_supply: uint256 = self.totalSupply
    self._checkpoint_rewards(addr, total_supply, False, ZERO_ADDRESS, True)

    self._update_liquidity_limit(addr, self.balanceOf[addr], total_supply)


@external
@nonreentrant('lock')
def deposit(_value: uint256, _addr: address , _claim_rewards: bool = False):
    """

    @notice Deposit `_value` LP tokens

    @dev Depositting also claims pending reward tokens

    @param _value Number of tokens to deposit

    @param _addr Address to deposit for

    @param _claim_rewards Bool to claim reward on _checkpoint_rewards()

    """
    #only personal vault can deposit
    assert PoolRegistry(self.pool_registry).vaultMap(self.pid, _addr) == msg.sender, "!only personal vault" 

    total_supply: uint256 = self.totalSupply

    if _value != 0:
        is_rewards: bool = self.reward_count != 0
        if is_rewards:
            self._checkpoint_rewards(_addr, total_supply, _claim_rewards, ZERO_ADDRESS)

        total_supply += _value
        new_balance: uint256 = self.balanceOf[_addr] + _value

        self.balanceOf[_addr] = new_balance
        self.totalSupply = total_supply

        self._update_liquidity_limit(_addr, new_balance, total_supply)
    else:
        self._checkpoint_rewards(_addr, total_supply, False, ZERO_ADDRESS, True)

    log Deposit(_addr, _value)

@external
@nonreentrant('lock')
def withdraw(_value: uint256, _addr: address, _claim_rewards: bool = False):
    """

    @notice Withdraw `_value` LP tokens

    @dev Withdrawing also claims pending reward tokens

    @param _value Number of tokens to withdraw

    @param _addr Address to withdraw for

    @param _claim_rewards Bool to claim reward on _checkpoint_rewards()

    """
    assert PoolRegistry(self.pool_registry).vaultMap(self.pid, _addr) == msg.sender, "!only personal vault" 
    total_supply: uint256 = self.totalSupply

    if _value != 0:
        is_rewards: bool = self.reward_count != 0
        if is_rewards:
            self._checkpoint_rewards(_addr, total_supply, _claim_rewards, ZERO_ADDRESS)

        total_supply -= _value
        new_balance: uint256 = self.balanceOf[_addr] - _value
        self.balanceOf[_addr] = new_balance
        self.totalSupply = total_supply

        self._update_liquidity_limit(_addr, new_balance, total_supply)
    else:
        self._checkpoint_rewards(_addr, total_supply, False, ZERO_ADDRESS, True)

    log Withdraw(_addr, _value)

@external
def add_reward(_reward_token: address, _distributor: address):
    """

    @notice Set the active reward contract

    @param _reward_token Address for new reward token

    @param _distributor Address of _reward_token distributor

    """
    assert msg.sender == self.admin  # dev: only owner

    reward_count: uint256 = self.reward_count
    assert reward_count < MAX_REWARDS
    assert self.reward_data[_reward_token].distributor == ZERO_ADDRESS

    self.reward_data[_reward_token].distributor = _distributor
    self.reward_tokens[reward_count] = _reward_token
    self.reward_count = reward_count + 1

@external
def set_reward_distributor(_reward_token: address, _distributor: address):
    """

    @notice Change address for a existring reward token distributor

    @param _reward_token Address of the reward token

    @param _distributor New address of the distributor

    """
    current_distributor: address = self.reward_data[_reward_token].distributor

    assert msg.sender == current_distributor or msg.sender == self.admin
    assert current_distributor != ZERO_ADDRESS
    assert _distributor != ZERO_ADDRESS

    self.reward_data[_reward_token].distributor = _distributor

@external
def set_claimer(_claimer: address):
    """

    @notice Change address for claimer

    @param _claimer New address for claimer

    """
    assert msg.sender == self.admin
    assert _claimer != ZERO_ADDRESS

    self.claimer = _claimer

@external
@nonreentrant("lock")
def deposit_reward_token(_reward_token: address, _amount: uint256):
    """

    @notice Depositing new amount of reward token into this LGV4

    @param _reward_token Address of the reward token

    @param _amount Amount of reward token to be deposited

    """
    assert msg.sender == self.reward_data[_reward_token].distributor

    self._checkpoint_rewards(ZERO_ADDRESS, self.totalSupply, False, ZERO_ADDRESS)

    response: Bytes[32] = raw_call(
        _reward_token,
        concat(
            method_id("transferFrom(address,address,uint256)"),
            convert(msg.sender, bytes32),
            convert(self, bytes32),
            convert(_amount, bytes32),
        ),
        max_outsize=32,
    )
    if len(response) != 0:
        assert convert(response, bool)

    period_finish: uint256 = self.reward_data[_reward_token].period_finish
    if block.timestamp >= period_finish:
        self.reward_data[_reward_token].rate = _amount / WEEK
    else:
        remaining: uint256 = period_finish - block.timestamp
        leftover: uint256 = remaining * self.reward_data[_reward_token].rate
        self.reward_data[_reward_token].rate = (_amount + leftover) / WEEK

    self.reward_data[_reward_token].last_update = block.timestamp
    self.reward_data[_reward_token].period_finish = block.timestamp + WEEK

    log RewardDataUpdate(_reward_token,_amount)

@external
def commit_transfer_ownership(addr: address):
    """

    @notice Transfer ownership of Gauge to `addr`

    @param addr Address to have ownership transferred to

    """
    assert msg.sender == self.admin  # dev: admin only
    assert addr != ZERO_ADDRESS  # dev: future admin cannot be the 0 address

    self.future_admin = addr
    log CommitOwnership(addr)


@external
def accept_transfer_ownership():
    """

    @notice Accept a pending ownership transfer

    """
    _admin: address = self.future_admin
    assert msg.sender == _admin  # dev: future admin only

    self.admin = _admin
    log ApplyOwnership(_admin)