Skip to content
Verified contractPartialMIT

TokenTweakLockerSigned

Address0x9c6e26f49e55ea2e29203811d370dbad56c4f29b
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,402,062
Creation transaction
0x09a81d9372…47de55b09f

contracts/TokenTweakLockerSigned.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "./TicketAuth.sol";

// ============================================================
// LP Locker (ERC-20 LP tokens) -- signed-ticket edition
// Platform: TokenTweak
// Version: 2.0.0
//
// Same custody model as TokenTweakLocker 1.x, but locking requires a
// server-signed ticket instead of a stored on-chain fee. See TicketAuth.
// ============================================================

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

contract TokenTweakLockerSigned is TicketAuth {

    struct Lock {
        address token;        // LP token address
        address owner;        // who locked it
        uint256 amount;       // amount actually received and locked
        uint256 unlocksAt;    // unix timestamp
        bool    withdrawn;
    }

    uint256 public lockCount;
    mapping(uint256 => Lock) public locks;
    mapping(address => uint256[]) public locksByOwner;

    event Locked(uint256 indexed lockId, address indexed owner, address indexed token, uint256 amount, uint256 unlocksAt);
    event Withdrawn(uint256 indexed lockId, address indexed owner, uint256 amount);

    constructor(address _platform, address _signer)
        TicketAuth("TokenTweakLockerSigned", _platform, _signer)
    {}

    // Caller must have approved this contract for _amount of _token first.
    // The ticket (fee, deadline, ticketId, sig) comes from the TokenTweak server.
    function lock(
        address _token,
        uint256 _amount,
        uint256 _duration,
        uint256 _fee,
        uint256 _deadline,
        bytes32 _ticketId,
        bytes calldata _sig
    ) external payable nonReentrant returns (uint256 lockId) {
        _consumeTicket(_fee, _deadline, _ticketId, _sig);

        require(_amount > 0,            "Amount must be > 0");
        require(_duration >= 1 days,    "Minimum lock 1 day");
        require(_duration <= 1825 days, "Maximum lock 5 years");

        // Record what actually arrived, so fee-on-transfer tokens can't
        // leave a lock that promises more than the contract holds.
        uint256 balBefore = IERC20(_token).balanceOf(address(this));
        require(IERC20(_token).transferFrom(msg.sender, address(this), _amount), "Transfer failed");
        uint256 received = IERC20(_token).balanceOf(address(this)) - balBefore;
        require(received > 0, "Nothing received");

        lockId = lockCount++;
        uint256 unlocksAt = block.timestamp + _duration;

        locks[lockId] = Lock({
            token:     _token,
            owner:     msg.sender,
            amount:    received,
            unlocksAt: unlocksAt,
            withdrawn: false
        });
        locksByOwner[msg.sender].push(lockId);

        _forwardFee(_fee);

        emit Locked(lockId, msg.sender, _token, received, unlocksAt);
    }

    // Never needs a ticket: users can always get their tokens back.
    function withdraw(uint256 lockId) external nonReentrant {
        Lock storage l = locks[lockId];
        require(msg.sender == l.owner,          "Not lock owner");
        require(!l.withdrawn,                   "Already withdrawn");
        require(block.timestamp >= l.unlocksAt, "Still locked");

        l.withdrawn = true;
        require(IERC20(l.token).transfer(msg.sender, l.amount), "Transfer failed");

        emit Withdrawn(lockId, msg.sender, l.amount);
    }

    function getLock(uint256 lockId) external view returns (Lock memory) {
        return locks[lockId];
    }

    function getLocksByOwner(address _owner) external view returns (uint256[] memory) {
        return locksByOwner[_owner];
    }

    function isLocked(uint256 lockId) external view returns (bool) {
        Lock storage l = locks[lockId];
        return !l.withdrawn && block.timestamp < l.unlocksAt;
    }
}

contracts/TicketAuth.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

// ============================================================
// TokenTweak ticket authorisation (shared by the V2 and V3 lockers)
//
// A lock is only accepted together with a short-lived "ticket": an
// EIP-712 signature from a TokenTweak signer key that states
//   - which wallet may lock (user)
//   - the exact fee in wei that wallet must attach (fee; 0 = exempt)
//   - when the ticket expires (deadline)
//   - a unique id (ticketId) so each ticket works exactly once
// The server decides the fee at the moment of locking (live USD price),
// so the contract never stores or updates a price. Withdrawals never
// need a ticket, so users' funds never depend on the signing server.
// ============================================================
abstract contract TicketAuth {
    address public owner;
    address public platform;

    // Addresses allowed to sign tickets. Several can be active at once so a
    // key can be rotated with no downtime and no redeploy.
    mapping(address => bool) public isSigner;
    mapping(bytes32 => bool) public usedTickets;

    bytes32 private immutable _nameHash;
    uint256 private _entered = 1;

    bytes32 private constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant TICKET_TYPEHASH =
        keccak256("LockTicket(address user,uint256 fee,uint256 deadline,bytes32 ticketId)");
    bytes32 private constant VERSION_HASH = keccak256("2");

    // Upper bound for a canonical (non-malleable) ECDSA "s" value.
    uint256 private constant HALF_N =
        0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

    event TicketUsed(address indexed user, bytes32 indexed ticketId, uint256 fee);
    event SignerUpdated(address indexed signer, bool allowed);
    event PlatformUpdated(address indexed platform);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    constructor(string memory name_, address _platform, address _signer) {
        require(_platform != address(0) && _signer != address(0), "Zero address");
        _nameHash = keccak256(bytes(name_));
        owner = msg.sender;
        platform = _platform;
        isSigner[_signer] = true;
        emit OwnershipTransferred(address(0), msg.sender);
        emit PlatformUpdated(_platform);
        emit SignerUpdated(_signer, true);
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }

    modifier nonReentrant() {
        require(_entered == 1, "Reentrant call");
        _entered = 2;
        _;
        _entered = 1;
    }

    // ── Owner administration ────────────────────────────────────
    // Add a new signer first, then remove the old one: tickets live only
    // minutes, so rotation needs no downtime. Removing every signer stops
    // all new locks (withdrawals are unaffected) -- an emergency brake.
    function setSigner(address _signer, bool _allowed) external onlyOwner {
        require(_signer != address(0), "Zero address");
        isSigner[_signer] = _allowed;
        emit SignerUpdated(_signer, _allowed);
    }

    function setPlatform(address _platform) external onlyOwner {
        require(_platform != address(0), "Zero address");
        platform = _platform;
        emit PlatformUpdated(_platform);
    }

    function transferOwnership(address _newOwner) external onlyOwner {
        require(_newOwner != address(0), "Zero address");
        emit OwnershipTransferred(owner, _newOwner);
        owner = _newOwner;
    }

    // ── Ticket hashing (public so the server/tests can cross-check) ──
    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(DOMAIN_TYPEHASH, _nameHash, VERSION_HASH, block.chainid, address(this)));
    }

    function ticketDigest(address user, uint256 fee, uint256 deadline, bytes32 ticketId)
        public
        view
        returns (bytes32)
    {
        bytes32 structHash = keccak256(abi.encode(TICKET_TYPEHASH, user, fee, deadline, ticketId));
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash));
    }

    // ── Ticket verification (internal) ──────────────────────────
    // Validates and consumes a ticket for msg.sender. Must be called from a
    // payable function: the attached value has to equal the ticket's fee.
    function _consumeTicket(uint256 fee, uint256 deadline, bytes32 ticketId, bytes calldata sig) internal {
        require(block.timestamp <= deadline, "Ticket expired");
        require(msg.value == fee, "Wrong fee");
        require(!usedTickets[ticketId], "Ticket used");
        require(sig.length == 65, "Bad signature");

        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := calldataload(sig.offset)
            s := calldataload(add(sig.offset, 32))
            v := byte(0, calldataload(add(sig.offset, 64)))
        }
        if (v < 27) v += 27;
        require(v == 27 || v == 28, "Bad signature");
        require(uint256(s) <= HALF_N, "Bad signature");

        address signer = ecrecover(ticketDigest(msg.sender, fee, deadline, ticketId), v, r, s);
        require(signer != address(0) && isSigner[signer], "Invalid ticket");

        usedTickets[ticketId] = true;
        emit TicketUsed(msg.sender, ticketId, fee);
    }

    function _forwardFee(uint256 fee) internal {
        if (fee > 0) {
            (bool sent, ) = platform.call{value: fee}("");
            require(sent, "Fee forward failed");
        }
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "none"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.