// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { LibBytes } from "../libs/LibBytes.sol";
import { LibEIP712 } from "../libs/LibEIP712.sol";
import { LibDelegation } from "../libs/LibDelegation.sol";
import { LibPermit } from "../libs/LibPermit.sol";
import { SafeMath96 } from "../libs/SafeMath96.sol";
/**
* @title DDX
* @author DerivaDEX (Borrowed/inspired from Compound)
* @notice This is the native token contract for DerivaDEX. It
* implements the ERC-20 standard, with additional
* functionality to efficiently handle the governance aspect of
* the DerivaDEX ecosystem.
* @dev The contract makes use of some nonstandard types not seen in
* the ERC-20 standard. The DDX token makes frequent use of the
* uint96 data type, as opposed to the more standard uint256 type.
* Given the maintenance of arrays of balances, allowances, and
* voting checkpoints, this allows us to more efficiently pack
* data together, thereby resulting in cheaper transactions.
*/
contract DDX {
using SafeMath96 for uint96;
using SafeMath for uint256;
using LibBytes for bytes;
/// @notice ERC20 token name for this token
string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase
/// @notice ERC20 token symbol for this token
string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase
/// @notice ERC20 token decimals for this token
uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase
/// @notice Version number for this token. Used for EIP712 hashing.
string public constant version = "1"; // solhint-disable-line const-name-snakecase
/// @notice Max number of tokens to be issued (100 million DDX)
uint96 public constant MAX_SUPPLY = 100000000e18;
/// @notice Total number of tokens in circulation (50 million DDX)
uint96 public constant PRE_MINE_SUPPLY = 50000000e18;
/// @notice Issued supply of tokens
uint96 public issuedSupply;
/// @notice Current total/circulating supply of tokens
uint96 public totalSupply;
/// @notice Whether ownership has been transferred to the DAO
bool public ownershipTransferred;
/// @notice Address authorized to issue/mint DDX tokens
address public issuer;
mapping(address => mapping(address => uint96)) internal allowances;
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking vote count from given block
struct Checkpoint {
uint32 id;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint256 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint256) public numCheckpoints;
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice Emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice Emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance);
/// @notice Emitted when transfer takes place
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice Emitted when approval takes place
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new DDX token
*/
constructor() public {
// Set issuer to deploying address
issuer = msg.sender;
// Issue pre-mine token supply to deploying address and
// set the issued and circulating supplies to pre-mine amount
_transferTokensMint(msg.sender, PRE_MINE_SUPPLY);
}
/**
* @notice Transfer ownership of DDX token from the deploying
* address to the DerivaDEX Proxy/DAO
* @param _derivaDEXProxy DerivaDEX Proxy address
*/
function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external {
// Ensure deploying address is calling this, destination is not
// the zero address, and that ownership has never been
// transferred thus far
require(msg.sender == issuer, "DDX: unauthorized transfer of ownership.");
require(_derivaDEXProxy != address(0), "DDX: transferring to zero address.");
require(!ownershipTransferred, "DDX: ownership already transferred.");
// Set ownership transferred boolean flag and the new authorized
// issuer
ownershipTransferred = true;
issuer = _derivaDEXProxy;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param _spender The address of the account which may transfer tokens
* @param _amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address _spender, uint256 _amount) external returns (bool) {
require(_spender != address(0), "DDX: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Set allowance
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
* Requirements:
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) {
require(_spender != address(0), "DDX: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_addedValue == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_addedValue, "DDX: amount exceeds 96 bits.");
}
// Increase allowance
allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount);
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* Emits an {Approval} event indicating the updated allowance.
* Requirements:
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) {
require(_spender != address(0), "DDX: approve to the zero address.");
// Convert amount to uint96
uint96 amount;
if (_subtractedValue == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits.");
}
// Decrease allowance
allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96(
amount,
"DDX: decreased allowance below zero."
);
emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param _account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address _account) external view returns (uint256) {
return balances[_account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param _recipient The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address _recipient, uint256 _amount) external returns (bool) {
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Transfer tokens from sender to recipient
_transferTokens(msg.sender, _recipient, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param _from The address of the source account
* @param _recipient The address of the destination account
* @param _amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address _from,
address _recipient,
uint256 _amount
) external returns (bool) {
uint96 spenderAllowance = allowances[_from][msg.sender];
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
if (msg.sender != _from && spenderAllowance != uint96(-1)) {
// Tx sender is not the same as transfer sender and doesn't
// have unlimited allowance.
// Reduce allowance by amount being transferred
uint96 newAllowance = spenderAllowance.sub96(amount);
allowances[_from][msg.sender] = newAllowance;
emit Approval(_from, msg.sender, newAllowance);
}
// Transfer tokens from sender to recipient
_transferTokens(_from, _recipient, amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function mint(address _recipient, uint256 _amount) external {
require(msg.sender == issuer, "DDX: unauthorized mint.");
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Ensure the mint doesn't cause the issued supply to exceed
// the total supply that could ever be issued
require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded.");
// Mint tokens to recipient
_transferTokensMint(_recipient, amount);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, decreasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function burn(uint256 _amount) external {
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
// Burn tokens from sender
_transferTokensBurn(msg.sender, amount);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function burnFrom(address _account, uint256 _amount) external {
uint96 spenderAllowance = allowances[_account][msg.sender];
// Convert amount to uint96
uint96 amount;
if (_amount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_amount, "DDX: amount exceeds 96 bits.");
}
if (msg.sender != _account && spenderAllowance != uint96(-1)) {
// Tx sender is not the same as burn account and doesn't
// have unlimited allowance.
// Reduce allowance by amount being transferred
uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance.");
allowances[_account][msg.sender] = newAllowance;
emit Approval(_account, msg.sender, newAllowance);
}
// Burn tokens from account
_transferTokensBurn(_account, amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param _delegatee The address to delegate votes to
*/
function delegate(address _delegatee) external {
_delegate(msg.sender, _delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param _delegatee The address to delegate votes to
* @param _nonce The contract state required to match the signature
* @param _expiry The time at which to expire the signature
* @param _signature Signature
*/
function delegateBySig(
address _delegatee,
uint256 _nonce,
uint256 _expiry,
bytes memory _signature
) external {
// Perform EIP712 hashing logic
bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 delegationHash =
LibDelegation.getDelegationHash(
LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }),
eip712OrderParamsDomainHash
);
// Perform sig recovery
uint8 v = uint8(_signature[0]);
bytes32 r = _signature.readBytes32(1);
bytes32 s = _signature.readBytes32(33);
address recovered = ecrecover(delegationHash, v, r, s);
require(recovered != address(0), "DDX: invalid signature.");
require(_nonce == nonces[recovered]++, "DDX: invalid nonce.");
require(block.timestamp <= _expiry, "DDX: signature expired.");
// Delegate votes from recovered address to delegatee
_delegate(recovered, _delegatee);
}
/**
* @notice Permits allowance from signatory to `spender`
* @param _spender The spender being approved
* @param _value The value being approved
* @param _nonce The contract state required to match the signature
* @param _expiry The time at which to expire the signature
* @param _signature Signature
*/
function permit(
address _spender,
uint256 _value,
uint256 _nonce,
uint256 _expiry,
bytes memory _signature
) external {
// Perform EIP712 hashing logic
bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this));
bytes32 permitHash =
LibPermit.getPermitHash(
LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }),
eip712OrderParamsDomainHash
);
// Perform sig recovery
uint8 v = uint8(_signature[0]);
bytes32 r = _signature.readBytes32(1);
bytes32 s = _signature.readBytes32(33);
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
address recovered = ecrecover(permitHash, v, r, s);
require(recovered != address(0), "DDX: invalid signature.");
require(_nonce == nonces[recovered]++, "DDX: invalid nonce.");
require(block.timestamp <= _expiry, "DDX: signature expired.");
// Convert amount to uint96
uint96 amount;
if (_value == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(_value, "DDX: amount exceeds 96 bits.");
}
// Set allowance
allowances[recovered][_spender] = amount;
emit Approval(recovered, _spender, _value);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param _account The address of the account holding the funds
* @param _spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address _account, address _spender) external view returns (uint256) {
return allowances[_account][_spender];
}
/**
* @notice Gets the current votes balance.
* @param _account The address to get votes balance.
* @return The number of current votes.
*/
function getCurrentVotes(address _account) external view returns (uint96) {
uint256 numCheckpointsAccount = numCheckpoints[_account];
return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param _account The address of the account to check
* @param _blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address _account, uint256 _blockNumber) external view returns (uint96) {
require(_blockNumber < block.number, "DDX: block not yet determined.");
uint256 numCheckpointsAccount = numCheckpoints[_account];
if (numCheckpointsAccount == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) {
return checkpoints[_account][numCheckpointsAccount - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[_account][0].id > _blockNumber) {
return 0;
}
// Perform binary search to find the most recent token holdings
// leading to a measure of voting power
uint256 lower = 0;
uint256 upper = numCheckpointsAccount - 1;
while (upper > lower) {
// ceil, avoiding overflow
uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[_account][center];
if (cp.id == _blockNumber) {
return cp.votes;
} else if (cp.id < _blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[_account][lower].votes;
}
function _delegate(address _delegator, address _delegatee) internal {
// Get the current address delegator has delegated
address currentDelegate = _getDelegatee(_delegator);
// Get delegator's DDX balance
uint96 delegatorBalance = balances[_delegator];
// Set delegator's new delegatee address
delegates[_delegator] = _delegatee;
emit DelegateChanged(_delegator, currentDelegate, _delegatee);
// Move votes from currently-delegated address to
// new address
_moveDelegates(currentDelegate, _delegatee, delegatorBalance);
}
function _transferTokens(
address _spender,
address _recipient,
uint96 _amount
) internal {
require(_spender != address(0), "DDX: cannot transfer from the zero address.");
require(_recipient != address(0), "DDX: cannot transfer to the zero address.");
// Reduce spender's balance and increase recipient balance
balances[_spender] = balances[_spender].sub96(_amount);
balances[_recipient] = balances[_recipient].add96(_amount);
emit Transfer(_spender, _recipient, _amount);
// Move votes from currently-delegated address to
// recipient's delegated address
_moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount);
}
function _transferTokensMint(address _recipient, uint96 _amount) internal {
require(_recipient != address(0), "DDX: cannot transfer to the zero address.");
// Add to recipient's balance
balances[_recipient] = balances[_recipient].add96(_amount);
// Increase the issued supply and circulating supply
issuedSupply = issuedSupply.add96(_amount);
totalSupply = totalSupply.add96(_amount);
emit Transfer(address(0), _recipient, _amount);
// Add delegates to recipient's delegated address
_moveDelegates(address(0), _getDelegatee(_recipient), _amount);
}
function _transferTokensBurn(address _spender, uint96 _amount) internal {
require(_spender != address(0), "DDX: cannot transfer from the zero address.");
// Reduce the spender/burner's balance
balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn.");
// Reduce the total supply
totalSupply = totalSupply.sub96(_amount);
emit Transfer(_spender, address(0), _amount);
// MRedduce delegates from spender's delegated address
_moveDelegates(_getDelegatee(_spender), address(0), _amount);
}
function _moveDelegates(
address _initDel,
address _finDel,
uint96 _amount
) internal {
if (_initDel != _finDel && _amount > 0) {
// Initial delegated address is different than final
// delegated address and nonzero number of votes moved
if (_initDel != address(0)) {
uint256 initDelNum = numCheckpoints[_initDel];
// Retrieve and compute the old and new initial delegate
// address' votes
uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0;
uint96 initDelNew = initDelOld.sub96(_amount);
_writeCheckpoint(_initDel, initDelOld, initDelNew);
}
if (_finDel != address(0)) {
uint256 finDelNum = numCheckpoints[_finDel];
// Retrieve and compute the old and new final delegate
// address' votes
uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0;
uint96 finDelNew = finDelOld.add96(_amount);
_writeCheckpoint(_finDel, finDelOld, finDelNew);
}
}
}
function _writeCheckpoint(
address _delegatee,
uint96 _oldVotes,
uint96 _newVotes
) internal {
uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits.");
uint256 delNum = numCheckpoints[_delegatee];
if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) {
// If latest checkpoint is current block, edit in place
checkpoints[_delegatee][delNum - 1].votes = _newVotes;
} else {
// Create a new id, vote pair
checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes });
numCheckpoints[_delegatee] = delNum.add(1);
}
emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes);
}
function _getDelegatee(address _delegator) internal view returns (address) {
if (delegates[_delegator] == address(0)) {
return _delegator;
}
return delegates[_delegator];
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) {
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) {
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
) internal pure {
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {
} lt(source, sEnd) {
} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {
} slt(dest, dEnd) {
} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
) internal pure returns (bytes memory result) {
require(from <= to, "FROM_LESS_THAN_TO_REQUIRED");
require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED");
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(result.contentAddress(), b.contentAddress() + from, result.length);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
) internal pure returns (bytes memory result) {
require(from <= to, "FROM_LESS_THAN_TO_REQUIRED");
require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED");
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b) internal pure returns (bytes1 result) {
require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED");
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b) internal pure returns (address result) {
require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED");
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) {
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(bytes memory b, uint256 index) internal pure returns (address result) {
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
) internal pure {
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) {
require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED");
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
) internal pure {
require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED");
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) {
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
) internal pure {
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) {
require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED");
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) {
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED");
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
) internal pure {
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(bytes memory dest, bytes memory source) internal pure {
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED");
memCopy(dest.contentAddress(), source.contentAddress(), sourceLen);
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
import { LibEIP712 } from "./LibEIP712.sol";
library LibDelegation {
struct Delegation {
address delegatee; // Delegatee
uint256 nonce; // Nonce
uint256 expiry; // Expiry
}
// Hash for the EIP712 OrderParams Schema
// bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked(
// "Delegation(",
// "address delegatee,",
// "uint256 nonce,",
// "uint256 expiry",
// ")"
// ));
bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH =
0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf;
/// @dev Calculates Keccak-256 hash of the delegation.
/// @param delegation The delegation structure.
/// @return delegationHash Keccak-256 EIP712 hash of the delegation.
function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 delegationHash)
{
delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation));
return delegationHash;
}
/// @dev Calculates EIP712 hash of the delegation.
/// @param delegation The delegation structure.
/// @return result EIP712 hash of the delegation.
function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH;
assembly {
// Assert delegation offset (this is an internal error that should never be triggered)
if lt(delegation, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(delegation, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 128)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
) internal pure returns (bytes32 result) {
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) {
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// SPDX-License-Identifier: MIT
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.12;
import { LibEIP712 } from "./LibEIP712.sol";
library LibPermit {
struct Permit {
address spender; // Spender
uint256 value; // Value
uint256 nonce; // Nonce
uint256 expiry; // Expiry
}
// Hash for the EIP712 LibPermit Schema
// bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked(
// "Permit(",
// "address spender,",
// "uint256 value,",
// "uint256 nonce,",
// "uint256 expiry",
// ")"
// ));
bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH =
0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7;
/// @dev Calculates Keccak-256 hash of the permit.
/// @param permit The permit structure.
/// @return permitHash Keccak-256 EIP712 hash of the permit.
function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 permitHash)
{
permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit));
return permitHash;
}
/// @dev Calculates EIP712 hash of the permit.
/// @param permit The permit structure.
/// @return result EIP712 hash of the permit.
function hashPermit(Permit memory permit) internal pure returns (bytes32 result) {
// Assembly for more efficiently computing:
bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH;
assembly {
// Assert permit offset (this is an internal error that should never be triggered)
if lt(permit, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(permit, 32)
// Backup
let temp1 := mload(pos1)
// Hash in place
mstore(pos1, schemaHash)
result := keccak256(pos1, 160)
// Restore
mstore(pos1, temp1)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath96 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add96(uint96 a, uint96 b) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub96(uint96 a, uint96 b) internal pure returns (uint96) {
return sub96(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
uint96 c = a - b;
return c;
}
}
{
"compilationTarget": {
"contracts/tokens/DDX.sol": "DDX"
},
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"details": {
"constantOptimizer": true,
"cse": true,
"deduplicate": true,
"jumpdestRemover": true,
"orderLiterals": true,
"peephole": true,
"yul": false
},
"runs": 50000
},
"remappings": []
}
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"delegator","type":"address"},{"indexed":true,"internalType":"address","name":"fromDelegate","type":"address"},{"indexed":true,"internalType":"address","name":"toDelegate","type":"address"}],"name":"DelegateChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"delegate","type":"address"},{"indexed":false,"internalType":"uint96","name":"previousBalance","type":"uint96"},{"indexed":false,"internalType":"uint96","name":"newBalance","type":"uint96"}],"name":"DelegateVotesChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRE_MINE_SUPPLY","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"},{"internalType":"address","name":"_spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"checkpoints","outputs":[{"internalType":"uint32","name":"id","type":"uint32"},{"internalType":"uint96","name":"votes","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_delegatee","type":"address"}],"name":"delegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_delegatee","type":"address"},{"internalType":"uint256","name":"_nonce","type":"uint256"},{"internalType":"uint256","name":"_expiry","type":"uint256"},{"internalType":"bytes","name":"_signature","type":"bytes"}],"name":"delegateBySig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"delegates","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"getCurrentVotes","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"},{"internalType":"uint256","name":"_blockNumber","type":"uint256"}],"name":"getPriorVotes","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"issuedSupply","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"issuer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"numCheckpoints","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ownershipTransferred","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"uint256","name":"_nonce","type":"uint256"},{"internalType":"uint256","name":"_expiry","type":"uint256"},{"internalType":"bytes","name":"_signature","type":"bytes"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_derivaDEXProxy","type":"address"}],"name":"transferOwnershipToDerivaDEXProxy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]