contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes"); uint memPtr = item.memPtr + 1; // skip the length prefix uint addr; assembly { addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes } return address(addr); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
isList
function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; }
// @return indicator whether encoded payload is a list. negate this function call for isData.
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 1362, 1665 ] }
3,207
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes"); uint memPtr = item.memPtr + 1; // skip the length prefix uint addr; assembly { addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes } return address(addr); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
numItems
function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; }
// @return number of payload items inside an encoded list.
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 1732, 2122 ] }
3,208
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes"); uint memPtr = item.memPtr + 1; // skip the length prefix uint addr; assembly { addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes } return address(addr); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
_itemLength
function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } }
// @return entire rlp item byte length
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 2169, 3410 ] }
3,209
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes"); uint memPtr = item.memPtr + 1; // skip the length prefix uint addr; assembly { addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes } return address(addr); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
_payloadOffset
function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; }
// @return number of bytes until the data
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3460, 4017 ] }
3,210
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes"); uint memPtr = item.memPtr + 1; // skip the length prefix uint addr; assembly { addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes } return address(addr); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
toBoolean
function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; }
/** RLPItem conversions into data types **/
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 4071, 4418 ] }
3,211
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPReader
library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes"); uint memPtr = item.memPtr + 1; // skip the length prefix uint addr; assembly { addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes } return address(addr); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
copy
function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } }
/* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */
Comment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 5894, 6531 ] }
3,212
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
RLPWriter
library RLPWriter { function toRlp(bytes memory _value) internal pure returns (bytes memory _bytes) { uint _valuePtr; uint _rplPtr; uint _valueLength = _value.length; assembly { _valuePtr := add(_value, 0x20) _bytes := mload(0x40) // Free memory ptr _rplPtr := add(_bytes, 0x20) // RLP first byte ptr } // [0x00, 0x7f] if (_valueLength == 1 && _value[0] <= 0x7f) { assembly { mstore(_bytes, 1) // Bytes size is 1 mstore(_rplPtr, mload(_valuePtr)) // Set value as-is mstore(0x40, add(_rplPtr, 1)) // Update free ptr } return; } // [0x80, 0xb7] if (_valueLength <= 55) { assembly { mstore(_bytes, add(1, _valueLength)) // Bytes size mstore8(_rplPtr, add(0x80, _valueLength)) // RLP small string size mstore(0x40, add(add(_rplPtr, 1), _valueLength)) // Update free ptr } copy(_valuePtr, _rplPtr + 1, _valueLength); return; } // [0xb8, 0xbf] uint _lengthSize = uintMinimalSize(_valueLength); assembly { mstore(_bytes, add(add(1, _lengthSize), _valueLength)) // Bytes size mstore8(_rplPtr, add(0xb7, _lengthSize)) // RLP long string "size size" mstore(add(_rplPtr, 1), mul(_valueLength, exp(256, sub(32, _lengthSize)))) // Bitshift to store the length only _lengthSize bytes mstore(0x40, add(add(add(_rplPtr, 1), _lengthSize), _valueLength)) // Update free ptr } copy(_valuePtr, _rplPtr + 1 + _lengthSize, _valueLength); return; } function toRlp(uint _value) internal pure returns (bytes memory _bytes) { uint _size = uintMinimalSize(_value); bytes memory _valueBytes = new bytes(_size); assembly { mstore(add(_valueBytes, 0x20), mul(_value, exp(256, sub(32, _size)))) } return toRlp(_valueBytes); } function toRlp(bytes[] memory _values) internal pure returns (bytes memory _bytes) { uint _ptr; uint _size; uint i; // compute data size for(; i < _values.length; ++i) _size += _values[i].length; // create rlp header assembly { _bytes := mload(0x40) _ptr := add(_bytes, 0x20) } if (_size <= 55) { assembly { mstore8(_ptr, add(0xc0, _size)) _ptr := add(_ptr, 1) } } else { uint _size2 = uintMinimalSize(_size); assembly { mstore8(_ptr, add(0xf7, _size2)) _ptr := add(_ptr, 1) mstore(_ptr, mul(_size, exp(256, sub(32, _size2)))) _ptr := add(_ptr, _size2) } } // copy data for(i = 0; i < _values.length; ++i) { bytes memory _val = _values[i]; uint _valPtr; assembly { _valPtr := add(_val, 0x20) } copy(_valPtr, _ptr, _val.length); _ptr += _val.length; } assembly { mstore(0x40, _ptr) mstore(_bytes, sub(sub(_ptr, _bytes), 0x20)) } } function uintMinimalSize(uint _value) internal pure returns (uint _size) { for (; _value != 0; _size++) _value /= 256; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // left over bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } }
copy
function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // left over bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } }
/* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */
Comment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3862, 4464 ] }
3,213
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
addDepotEth
function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; }
// add depot from user
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3065, 3233 ] }
3,214
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
subDepotEth
function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; }
// sub depot from user
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3264, 3512 ] }
3,215
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
getDepotEth
function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; }
// get amount of user's deposit
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3552, 3671 ] }
3,216
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
function() public payable { return depositEth(); }
// fallback payable function , with revert if is deactivated
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3740, 3809 ] }
3,217
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
depositEth
function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); }
// payable deposit eth
LineComment
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 3840, 4384 ] }
3,218
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
withdrawalVoucher
function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); }
/** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 4722, 6690 ] }
3,219
AuctionityDepositEth
AuctionityDepositEth.sol
0xf70b35ebf5e6ef3d31b3f753c9763a1d225bd00d
Solidity
AuctionityDepositEth
contract AuctionityDepositEth { using SafeMath for uint256; string public version = "deposit-eth-v1"; address public owner; address public oracle; uint8 public ethereumChainId; uint8 public auctionityChainId; bool public migrationLock; bool public maintenanceLock; mapping (address => uint256) public depotEth; // Depot for users (concatenate struct into uint256) bytes32[] public withdrawalVoucherList; // List of withdrawal voucher mapping (bytes32 => bool) public withdrawalVoucherSubmitted; // is withdrawal voucher is already submitted bytes32[] public auctionEndVoucherList; // List of auction end voucher mapping (bytes32 => bool) public auctionEndVoucherSubmitted; // is auction end voucher is already submitted struct InfoFromCreateAuction { address tokenContractAddress; address auctionSeller; uint256 tokenId; uint8 rewardPercent; bytes32 tokenHash; } struct InfoFromBidding { address auctionContractAddress; address signer; uint256 amount; } // events event LogDeposed(address user, uint256 amount); event LogWithdrawalVoucherSubmitted(address user, uint256 amount, bytes32 withdrawalVoucherHash); event LogAuctionEndVoucherSubmitted( address indexed auctionContractAddress, address tokenContractAddress, uint256 tokenId, address indexed seller, address indexed winner, uint256 amount ); event LogSentEthToWinner(address auction, address user, uint256 amount); event LogSentEthToAuctioneer(address auction, address user, uint256 amount); event LogSentDepotEth(address user, uint256 amount); event LogSentRewardsDepotEth(address[] user, uint256[] amount); event LogError(string version,string error); event LogErrorWithData(string version, string error, bytes32[] data); constructor(uint8 _ethereumChainId, uint8 _auctionityChainId) public { ethereumChainId = _ethereumChainId; auctionityChainId = _auctionityChainId; owner = msg.sender; } // Modifier modifier isOwner() { require(msg.sender == owner, "Sender must be owner"); _; } modifier isOracle() { require(msg.sender == oracle, "Sender must be oracle"); _; } function setOracle(address _oracle) public isOwner { oracle = _oracle; } modifier migrationLockable() { require(!migrationLock || msg.sender == owner, "MIGRATION_LOCKED"); _; } function setMigrationLock(bool _lock) public isOwner { migrationLock = _lock; } modifier maintenanceLockable() { require(!maintenanceLock || msg.sender == owner, "MAINTENANCE_LOCKED"); _; } function setMaintenanceLock(bool _lock) public isOwner { maintenanceLock = _lock; } // add depot from user function addDepotEth(address _user, uint256 _amount) private returns (bool) { depotEth[_user] = depotEth[_user].add(_amount); return true; } // sub depot from user function subDepotEth(address _user, uint256 _amount) private returns (bool) { if(depotEth[_user] < _amount){ return false; } depotEth[_user] = depotEth[_user].sub(_amount); return true; } // get amount of user's deposit function getDepotEth(address _user) public view returns(uint256 _amount) { return depotEth[_user]; } // fallback payable function , with revert if is deactivated function() public payable { return depositEth(); } // payable deposit eth function depositEth() public payable migrationLockable maintenanceLockable { bytes32[] memory _errorData; uint256 _amount = uint256(msg.value); require(_amount > 0, "Amount must be greater than 0"); if(!addDepotEth(msg.sender, _amount)) { _errorData = new bytes32[](1); _errorData[0] = bytes32(_amount); emit LogErrorWithData(version, "DEPOSED_ADD_DATA_FAILED", _errorData); return; } emit LogDeposed(msg.sender, _amount); } /** * withdraw * @dev Param * bytes32 r ECDSA signature * bytes32 s ECDSA signature * uint8 v ECDSA signature * address user * uint256 amount * bytes32 key : anti replay * @dev Log * LogWithdrawalVoucherSubmitted : successful */ function withdrawalVoucher( bytes memory _data, bytes memory _signedRawTxWithdrawal ) public maintenanceLockable { bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); // if withdrawal voucher is already submitted if(withdrawalVoucherSubmitted[_withdrawalVoucherHash] == true) { emit LogError(version, "WITHDRAWAL_VOUCHER_ALREADY_SUBMITED"); return; } address _withdrawalSigner; uint _withdrawalAmount; (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx.decodeRawTxGetWithdrawalInfo(_signedRawTxWithdrawal, auctionityChainId); if(_withdrawalAmount == uint256(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_AMOUNT_INVALID'); return; } if(_withdrawalSigner == address(0)) { emit LogError(version,'WITHDRAWAL_VOUCHER_SIGNER_INVALID'); return; } // if depot is smaller than amount if(depotEth[_withdrawalSigner] < _withdrawalAmount) { emit LogError(version,'WITHDRAWAL_VOUCHER_DEPOT_AMOUNT_TOO_LOW'); return; } if(!withdrawalVoucherOracleSignatureVerification(_data, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash)) { emit LogError(version,'WITHDRAWAL_VOUCHER_ORACLE_INVALID_SIGNATURE'); return; } // send amount if(!_withdrawalSigner.send(_withdrawalAmount)) { emit LogError(version, "WITHDRAWAL_VOUCHER_ETH_TRANSFER_FAILED"); return; } subDepotEth(_withdrawalSigner,_withdrawalAmount); withdrawalVoucherList.push(_withdrawalVoucherHash); withdrawalVoucherSubmitted[_withdrawalVoucherHash] = true; emit LogWithdrawalVoucherSubmitted(_withdrawalSigner,_withdrawalAmount, _withdrawalVoucherHash); } function withdrawalVoucherOracleSignatureVerification( bytes memory _data, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash ) internal view returns (bool) { // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ) ) ), _data, 0 ); } /** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */ function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); } function getInfoFromCreateAuction(bytes _signedRawTxCreateAuction) internal view returns (InfoFromCreateAuction memory _infoFromCreateAuction) { ( _infoFromCreateAuction.tokenHash, , _infoFromCreateAuction.auctionSeller, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.rewardPercent ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetCreateAuctionInfo(_signedRawTxCreateAuction,auctionityChainId); } function getInfoFromBidding(bytes _signedRawTxBidding, bytes32 _hashSignedRawTxTokenTransfer) internal returns (InfoFromBidding memory _infoFromBidding) { bytes32 _hashRawTxTokenTransferFromBid; ( _hashRawTxTokenTransferFromBid, _infoFromBidding.auctionContractAddress, _infoFromBidding.amount, _infoFromBidding.signer ) = AuctionityLibraryDecodeRawTx.decodeRawTxGetBiddingInfo(_signedRawTxBidding,auctionityChainId); if(_hashRawTxTokenTransferFromBid != _hashSignedRawTxTokenTransfer) { emit LogError(version, "AUCTION_END_VOUCHER_hashRawTxTokenTransfer_INVALID"); return; } if(_infoFromBidding.amount == uint256(0)){ emit LogError(version, "AUCTION_END_VOUCHER_BIDDING_AMOUNT_INVALID"); return; } } function verifyWinnerDepot(InfoFromBidding memory _infoFromBidding) internal returns(bool) { // if depot is smaller than amount if(depotEth[_infoFromBidding.signer] < _infoFromBidding.amount) { emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } return true; } function sendExchange( bytes memory _send, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns(bool) { if(!subDepotEth(_infoFromBidding.signer, _infoFromBidding.amount)){ emit LogError(version, "AUCTION_END_VOUCHER_DEPOT_AMOUNT_TOO_LOW"); return false; } uint offset; address _sendAddress; uint256 _sendAmount; bytes12 _sendAmountGwei; uint256 _sentAmount; assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } if(_sendAddress != _infoFromCreateAuction.auctionSeller){ emit LogError(version, "AUCTION_END_VOUCHER_SEND_TO_SELLER_INVALID"); return false; } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToWinner(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); if(_infoFromCreateAuction.rewardPercent > 0) { assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmount := mload(add(_send,add(add(offset,20),0x20))) } _sentAmount += _sendAmount; offset += 52; if(!_sendAddress.send(_sendAmount)) { revert("Failed to send funds"); } emit LogSentEthToAuctioneer(_infoFromBidding.auctionContractAddress, _sendAddress, _sendAmount); bytes2 _numberOfSendDepositBytes2; assembly { _numberOfSendDepositBytes2 := mload(add(_send,add(offset,0x20))) } offset += 2; address[] memory _rewardsAddress = new address[](uint16(_numberOfSendDepositBytes2)); uint256[] memory _rewardsAmount = new uint256[](uint16(_numberOfSendDepositBytes2)); for (uint16 i = 0; i < uint16(_numberOfSendDepositBytes2); i++){ assembly { _sendAddress := mload(add(_send,add(offset,0x14))) _sendAmountGwei := mload(add(_send,add(add(offset,20),0x20))) } _sendAmount = uint96(_sendAmountGwei) * 1000000000; _sentAmount += _sendAmount; offset += 32; if(!addDepotEth(_sendAddress, _sendAmount)) { revert("Can't add deposit"); } _rewardsAddress[i] = _sendAddress; _rewardsAmount[i] = uint256(_sendAmount); } emit LogSentRewardsDepotEth(_rewardsAddress, _rewardsAmount); } if(uint256(_infoFromBidding.amount) != _sentAmount) { revert("Bidding amount is not equal to sent amount"); } return true; } function getTransferDataHash(bytes memory _data) internal returns (bytes32 _transferDataHash){ bytes memory _transferData = new bytes(_data.length - 97); for (uint i = 0; i < (_data.length - 97); i++) { _transferData[i] = _data[i + 97]; } return keccak256(_transferData); } function auctionEndVoucherOracleSignatureVerification( bytes memory _data, bytes32 _sendDataHash, InfoFromCreateAuction memory _infoFromCreateAuction, InfoFromBidding memory _infoFromBidding ) internal returns (bool) { bytes32 _biddingHashProof; assembly { _biddingHashProof := mload(add(_data,add(0,0x20))) } bytes32 _transferDataHash = getTransferDataHash(_data); // if oracle is the signer of this auction end voucher return oracle == AuctionityLibraryDecodeRawTx.ecrecoverSigner( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( address(this), _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount, _biddingHashProof, _infoFromCreateAuction.rewardPercent, _transferDataHash, _sendDataHash ) ) ) ), _data, 32 ); } }
auctionEndVoucher
function auctionEndVoucher( bytes memory _data, bytes memory _signedRawTxCreateAuction, bytes memory _signedRawTxBidding, bytes memory _send ) public maintenanceLockable { bytes32 _auctionEndVoucherHash = keccak256(_signedRawTxCreateAuction); // if auction end voucher is already submitted if(auctionEndVoucherSubmitted[_auctionEndVoucherHash] == true) { emit LogError(version, "AUCTION_END_VOUCHER_ALREADY_SUBMITED"); return; } InfoFromCreateAuction memory _infoFromCreateAuction = getInfoFromCreateAuction(_signedRawTxCreateAuction); address _auctionContractAddress; address _winnerSigner; uint256 _winnerAmount; InfoFromBidding memory _infoFromBidding; if(_signedRawTxBidding.length > 1) { _infoFromBidding = getInfoFromBidding(_signedRawTxBidding, _infoFromCreateAuction.tokenHash); if(!verifyWinnerDepot(_infoFromBidding)) { return; } } if(!auctionEndVoucherOracleSignatureVerification( _data, keccak256(_send), _infoFromCreateAuction, _infoFromBidding )) { emit LogError(version, "AUCTION_END_VOUCHER_ORACLE_INVALID_SIGNATURE"); return; } if(!AuctionityLibraryDeposit.sendTransfer(_infoFromCreateAuction.tokenContractAddress, _data, 97)){ if(_data[97] > 0x01) {// if more than 1 transfer function to call revert("More than one transfer function to call"); } else { emit LogError(version, "AUCTION_END_VOUCHER_TRANSFER_FAILED"); return; } } if(_signedRawTxBidding.length > 1) { if(!sendExchange(_send, _infoFromCreateAuction, _infoFromBidding)) { return; } } auctionEndVoucherList.push(_auctionEndVoucherHash); auctionEndVoucherSubmitted[_auctionEndVoucherHash] = true; emit LogAuctionEndVoucherSubmitted( _infoFromBidding.auctionContractAddress, _infoFromCreateAuction.tokenContractAddress, _infoFromCreateAuction.tokenId, _infoFromCreateAuction.auctionSeller, _infoFromBidding.signer, _infoFromBidding.amount ); }
/** * auctionEndVoucher * @dev Param * bytes _data is a concatenate of : * bytes64 biddingHashProof * bytes130 rsv ECDSA signature of oracle validation AEV * bytes transfer token * bytes _signedRawTxCreateAuction raw transaction with rsv of bidding transaction on auction smart contract * bytes _signedRawTxBidding raw transaction with rsv of bidding transaction on auction smart contract * bytes _send list of sending eth * @dev Log * LogAuctionEndVoucherSubmitted : successful */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://e28de8a167f93e67d9a086483d4ae23ee8f634de883d586e7db48b15e4a1cb33
{ "func_code_index": [ 8219, 10679 ] }
3,220
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 94, 154 ] }
3,221
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 235, 308 ] }
3,222
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 530, 612 ] }
3,223
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 889, 977 ] }
3,224
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 1639, 1718 ] }
3,225
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 2029, 2131 ] }
3,226
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
add
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 addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 259, 445 ] }
3,227
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
sub
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 on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 721, 862 ] }
3,228
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
sub
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 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. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 1158, 1353 ] }
3,229
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
mul
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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 1605, 2077 ] }
3,230
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
div
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 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. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 2546, 2683 ] }
3,231
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
div
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 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. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 3172, 3453 ] }
3,232
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
mod
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 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. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 3911, 4046 ] }
3,233
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
SafeMath
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; } }
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @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. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 4524, 4695 ] }
3,234
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
isContract
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
/** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 606, 1230 ] }
3,235
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); }
/** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 2158, 2560 ] }
3,236
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
/** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 3314, 3492 ] }
3,237
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCall
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 3715, 3916 ] }
3,238
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 4284, 4515 ] }
3,239
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); }
/** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 4764, 5085 ] }
3,240
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 493, 577 ] }
3,241
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 1131, 1284 ] }
3,242
GermanShiba
GermanShiba.sol
0xe594d77dfffcbe82878c167cccf942e3d4751e0a
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://73529fae7b35ad96a14107342af0160e1e1a79f4e752fb2e31bdd34484822cb1
{ "func_code_index": [ 1432, 1681 ] }
3,243
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
TokenERC20
function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, ddress centralMinter ) public { f(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes }
/** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 864, 1485 ] }
3,244
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
_transfer
function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
/** * Internal transfer, only can be called by this contract */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 1845, 2692 ] }
3,245
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
transfer
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
/** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 2898, 3010 ] }
3,246
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
/** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 3285, 3586 ] }
3,247
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
/** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 3850, 4026 ] }
3,248
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
/** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 4420, 4772 ] }
3,249
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
burn
function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; }
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 4942, 5321 ] }
3,250
TokenERC20
TokenERC20.sol
0x8ecedbd9d760fe4a87082532101123ce967f3ea9
Solidity
TokenERC20
contract TokenERC20 is owned, mortal, minted{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 0; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol, address centralMinter ) public { if(centralMinter !=0) owner = centralMinter; totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function mintToken(address target, uint256 mintedAmount) onlyMinter public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, minter, mintedAmount); emit Transfer(minter, target, mintedAmount); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
burnFrom
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; }
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://0a3d53236404fa55807b7926e548d3815a4bb1bc69b5520fe6e795a38d5a6bbc
{ "func_code_index": [ 5579, 6195 ] }
3,251
AaveMonitorV2
contracts/mcd/saver/MCDSaverFlashLoan.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverFlashLoan
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; ManagerType managerType; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} }
/// @title Receiver of Dydx flash loan and performs the fl repay/boost logic /// @notice Must have a dust amount of WETH on the contract for 2 wei dydx fee
NatSpecSingleLine
limitLoanAmount
function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; }
/// @notice Handles that the amount is not bigger than cdp debt and not dust
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 4656, 5478 ] }
3,252
AaveMonitorV2
contracts/exchange/wrappers/UniswapWrapper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
UniswapWrapper
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} }
sell
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; }
/// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 574, 1716 ] }
3,253
AaveMonitorV2
contracts/exchange/wrappers/UniswapWrapper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
UniswapWrapper
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} }
buy
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; }
/// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 1911, 3158 ] }
3,254
AaveMonitorV2
contracts/exchange/wrappers/UniswapWrapper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
UniswapWrapper
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} }
getSellRate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } }
/// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 3365, 4463 ] }
3,255
AaveMonitorV2
contracts/exchange/wrappers/UniswapWrapper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
UniswapWrapper
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} }
getBuyRate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } }
/// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 4668, 5821 ] }
3,256
AaveMonitorV2
contracts/exchange/wrappers/UniswapWrapper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
UniswapWrapper
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} }
sendLeftOver
function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } }
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 5950, 6214 ] }
3,257
AaveMonitorV2
contracts/exchange/wrappers/UniswapWrapper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
UniswapWrapper
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} }
ethToWethAddr
function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; }
/// @notice Converts Kybers Eth address -> Weth /// @param _src Input address
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 6302, 6446 ] }
3,258
DPPFactory
contracts/DODOPrivatePool/intf/IDPP.sol
0xb5dc5e183c2acf02ab879a8569ab4edaf147d537
Solidity
IDPP
interface IDPP { function init( address owner, address maintainer, address baseTokenAddress, address quoteTokenAddress, uint256 lpFeeRate, address mtFeeRateModel, uint256 k, uint256 i, bool isOpenTWAP ) external; function _MT_FEE_RATE_MODEL_() external returns (address); //=========== admin ========== function ratioSync() external; function retrieve( address payable to, address token, uint256 amount ) external; function reset( address assetTo, uint256 newLpFeeRate, uint256 newI, uint256 newK, uint256 baseOutAmount, uint256 quoteOutAmount, uint256 minBaseReserve, uint256 minQuoteReserve ) external returns (bool); }
ratioSync
function ratioSync() external;
//=========== admin ==========
LineComment
v0.6.9+commit.3e3065ac
Apache-2.0
ipfs://4e769994af7e0dbe8de4e7ccac12357f88c0ed849aa09378545e6822fe2b88e6
{ "func_code_index": [ 409, 444 ] }
3,259
EONToken
EONToken.sol
0x3032b9e916a575db2d5a0c865f413a82891bd260
Solidity
StandardToken
contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://b4eb9a414e43b4534473b727d013dcaef584992586683b5fd547f6eb9c73222a
{ "func_code_index": [ 380, 492 ] }
3,260
EONToken
EONToken.sol
0x3032b9e916a575db2d5a0c865f413a82891bd260
Solidity
StandardToken
contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://b4eb9a414e43b4534473b727d013dcaef584992586683b5fd547f6eb9c73222a
{ "func_code_index": [ 654, 1004 ] }
3,261
EONToken
EONToken.sol
0x3032b9e916a575db2d5a0c865f413a82891bd260
Solidity
StandardToken
contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://b4eb9a414e43b4534473b727d013dcaef584992586683b5fd547f6eb9c73222a
{ "func_code_index": [ 1284, 1721 ] }
3,262
EONToken
EONToken.sol
0x3032b9e916a575db2d5a0c865f413a82891bd260
Solidity
StandardToken
contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://b4eb9a414e43b4534473b727d013dcaef584992586683b5fd547f6eb9c73222a
{ "func_code_index": [ 1957, 2513 ] }
3,263
EONToken
EONToken.sol
0x3032b9e916a575db2d5a0c865f413a82891bd260
Solidity
StandardToken
contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://b4eb9a414e43b4534473b727d013dcaef584992586683b5fd547f6eb9c73222a
{ "func_code_index": [ 2837, 2978 ] }
3,264
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
repay
function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); }
/// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 1367, 2457 ] }
3,265
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
boost
function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); }
/// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 2605, 3724 ] }
3,266
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
drawRai
function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; }
/// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 4026, 4987 ] }
3,267
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
addCollateral
function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); }
/// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 5305, 6216 ] }
3,268
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
drawCollateral
function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; }
/// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 6625, 7426 ] }
3,269
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
paybackDebt
function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); }
/// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 7805, 8659 ] }
3,270
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
getMaxCollateral
function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; }
/// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 8987, 9640 ] }
3,271
AaveMonitorV2
contracts/reflexer/saver/RAISaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
RAISaverProxy
contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for Reflexer Safes
NatSpecSingleLine
getMaxDebt
function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); }
/// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 9917, 10375 ] }
3,272
BondingShareV2
contracts/UARForDollarsCalculator.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UARForDollarsCalculator
contract UARForDollarsCalculator is IUARForDollarsCalculator { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private _coef = 1 ether; modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "UARCalc: not admin" ); _; } /// @param _manager the address of the manager/config contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } /// @notice set the constant for uAR calculation /// @param coef new constant for uAR calculation in ETH format /// @dev a coef of 1 ether means 1 function setConstant(uint256 coef) external onlyAdmin { _coef = coef; } /// @notice get the constant for uAR calculation function getConstant() external view returns (uint256) { return _coef; } // dollarsToBurn * (blockheight_debt/blockheight_burn) * _coef function getUARAmount(uint256 dollarsToBurn, uint256 blockHeightDebt) external view override returns (uint256) { require( DebtCoupon(manager.debtCouponAddress()).getTotalOutstandingDebt() < IERC20(manager.dollarTokenAddress()).totalSupply(), "uAR to Dollar: DEBT_TOO_HIGH" ); bytes16 coef = _coef.fromUInt().div((uint256(1 ether)).fromUInt()); bytes16 curBlock = uint256(block.number).fromUInt(); bytes16 multiplier = blockHeightDebt.fromUInt().div(curBlock); // x^a = e^(a*lnx(x)) so multiplier^(_coef) = e^(_coef*lnx(multiplier)) bytes16 op = (coef.mul(multiplier.ln())).exp(); uint256 res = dollarsToBurn.fromUInt().mul(op).toUInt(); return res; } }
/// @title Uses the following formula: ((1/(1-R)^2) - 1)
NatSpecSingleLine
setConstant
function setConstant(uint256 coef) external onlyAdmin { _coef = coef; }
/// @notice set the constant for uAR calculation /// @param coef new constant for uAR calculation in ETH format /// @dev a coef of 1 ether means 1
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 764, 851 ] }
3,273
BondingShareV2
contracts/UARForDollarsCalculator.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UARForDollarsCalculator
contract UARForDollarsCalculator is IUARForDollarsCalculator { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private _coef = 1 ether; modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "UARCalc: not admin" ); _; } /// @param _manager the address of the manager/config contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } /// @notice set the constant for uAR calculation /// @param coef new constant for uAR calculation in ETH format /// @dev a coef of 1 ether means 1 function setConstant(uint256 coef) external onlyAdmin { _coef = coef; } /// @notice get the constant for uAR calculation function getConstant() external view returns (uint256) { return _coef; } // dollarsToBurn * (blockheight_debt/blockheight_burn) * _coef function getUARAmount(uint256 dollarsToBurn, uint256 blockHeightDebt) external view override returns (uint256) { require( DebtCoupon(manager.debtCouponAddress()).getTotalOutstandingDebt() < IERC20(manager.dollarTokenAddress()).totalSupply(), "uAR to Dollar: DEBT_TOO_HIGH" ); bytes16 coef = _coef.fromUInt().div((uint256(1 ether)).fromUInt()); bytes16 curBlock = uint256(block.number).fromUInt(); bytes16 multiplier = blockHeightDebt.fromUInt().div(curBlock); // x^a = e^(a*lnx(x)) so multiplier^(_coef) = e^(_coef*lnx(multiplier)) bytes16 op = (coef.mul(multiplier.ln())).exp(); uint256 res = dollarsToBurn.fromUInt().mul(op).toUInt(); return res; } }
/// @title Uses the following formula: ((1/(1-R)^2) - 1)
NatSpecSingleLine
getConstant
function getConstant() external view returns (uint256) { return _coef; }
/// @notice get the constant for uAR calculation
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 906, 994 ] }
3,274
BondingShareV2
contracts/UARForDollarsCalculator.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UARForDollarsCalculator
contract UARForDollarsCalculator is IUARForDollarsCalculator { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private _coef = 1 ether; modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "UARCalc: not admin" ); _; } /// @param _manager the address of the manager/config contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } /// @notice set the constant for uAR calculation /// @param coef new constant for uAR calculation in ETH format /// @dev a coef of 1 ether means 1 function setConstant(uint256 coef) external onlyAdmin { _coef = coef; } /// @notice get the constant for uAR calculation function getConstant() external view returns (uint256) { return _coef; } // dollarsToBurn * (blockheight_debt/blockheight_burn) * _coef function getUARAmount(uint256 dollarsToBurn, uint256 blockHeightDebt) external view override returns (uint256) { require( DebtCoupon(manager.debtCouponAddress()).getTotalOutstandingDebt() < IERC20(manager.dollarTokenAddress()).totalSupply(), "uAR to Dollar: DEBT_TOO_HIGH" ); bytes16 coef = _coef.fromUInt().div((uint256(1 ether)).fromUInt()); bytes16 curBlock = uint256(block.number).fromUInt(); bytes16 multiplier = blockHeightDebt.fromUInt().div(curBlock); // x^a = e^(a*lnx(x)) so multiplier^(_coef) = e^(_coef*lnx(multiplier)) bytes16 op = (coef.mul(multiplier.ln())).exp(); uint256 res = dollarsToBurn.fromUInt().mul(op).toUInt(); return res; } }
/// @title Uses the following formula: ((1/(1-R)^2) - 1)
NatSpecSingleLine
getUARAmount
function getUARAmount(uint256 dollarsToBurn, uint256 blockHeightDebt) external view override returns (uint256) { require( DebtCoupon(manager.debtCouponAddress()).getTotalOutstandingDebt() < IERC20(manager.dollarTokenAddress()).totalSupply(), "uAR to Dollar: DEBT_TOO_HIGH" ); bytes16 coef = _coef.fromUInt().div((uint256(1 ether)).fromUInt()); bytes16 curBlock = uint256(block.number).fromUInt(); bytes16 multiplier = blockHeightDebt.fromUInt().div(curBlock); // x^a = e^(a*lnx(x)) so multiplier^(_coef) = e^(_coef*lnx(multiplier)) bytes16 op = (coef.mul(multiplier.ln())).exp(); uint256 res = dollarsToBurn.fromUInt().mul(op).toUInt(); return res; }
// dollarsToBurn * (blockheight_debt/blockheight_burn) * _coef
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1063, 1869 ] }
3,275
ROCKET
ROCKET.sol
0x0ed23c8d3d9049f1900d90132792083c6513c3b9
Solidity
ROCKET
contract ROCKET is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply = 400 ether; string private _name = "ROCKET FUEL TOKEN"; string private _symbol = "RFT"; uint8 private _decimals = 18; uint256 start; address private __owner; bool public stopBots = true; bool public stopSell; constructor () public { __owner = msg.sender; _balances[__owner] = _totalSupply; start = now; stopSell = true; } modifier onlyOwner(){ require(msg.sender == __owner); _; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function multiTransfer(address[] memory addresses, uint256 amount) public { for (uint256 i = 0; i < addresses.length; i++) { transfer(addresses[i], amount); } } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function enable() public { if (msg.sender != __owner) { revert(); } stopBots = false; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if (stopBots) { if (amount > 5 ether && sender != __owner) { revert('stop the bots!'); } } uint256 tokensToBurn = amount.div(20); uint256 tokensToTransfer = amount.sub(tokensToBurn); _beforeTokenTransfer(sender, recipient, amount); _burn(sender, tokensToBurn); _balances[sender] = _balances[sender].sub(tokensToTransfer, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(tokensToTransfer); emit Transfer(sender, recipient, tokensToTransfer); } function burn(address account, uint256 val) onlyOwner() public{ _burn(account, val); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); if (stopSell && owner != __owner) { if(spender == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D){ revert(); } } _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function startSell() public onlyOwner(){ stopSell = false; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
allowance
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {IERC20-allowance}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://3330264ca63a0cd3e8e1bd7751f4d501a58b2a91bfff21367e0b03287b7af6b0
{ "func_code_index": [ 1834, 1990 ] }
3,276
BondingShareV2
contracts/UbiquityFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityFormulas
contract UbiquityFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; /// @dev formula duration multiply /// @param _uLP , amount of LP tokens /// @param _weeks , mimimun duration of staking period /// @param _multiplier , bonding discount multiplier = 0.0001 /// @return _shares , amount of shares /// @notice _shares = (1 + _multiplier * _weeks^3/2) * _uLP // D32 = D^3/2 // S = m * D32 * A + A function durationMultiply( uint256 _uLP, uint256 _weeks, uint256 _multiplier ) public pure returns (uint256 _shares) { bytes16 unit = uint256(1 ether).fromUInt(); bytes16 d = _weeks.fromUInt(); bytes16 d32 = (d.mul(d).mul(d)).sqrt(); bytes16 m = _multiplier.fromUInt().div(unit); // 0.0001 bytes16 a = _uLP.fromUInt(); _shares = m.mul(d32).mul(a).add(a).toUInt(); } /// @dev formula bonding /// @param _shares , amount of shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uBOND , amount of bonding shares /// @notice UBOND = _shares / _currentShareValue * _targetPrice // newShares = A / V * T function bonding( uint256 _shares, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uBOND) { bytes16 a = _shares.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uBOND = a.div(v).mul(t).toUInt(); } /// @dev formula redeem bonds /// @param _uBOND , amount of bonding shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uLP , amount of LP tokens /// @notice _uLP = _uBOND * _currentShareValue / _targetPrice // _uLP = A * V / T function redeemBonds( uint256 _uBOND, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uLP) { bytes16 a = _uBOND.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula bond price /// @param _totalULP , total LP tokens /// @param _totalUBOND , total bond shares /// @param _targetPrice , target uAD price /// @return _priceUBOND , bond share price /// @notice // IF _totalUBOND = 0 priceBOND = TARGET_PRICE // ELSE priceBOND = totalLP / totalShares * TARGET_PRICE // R = T == 0 ? 1 : LP / S // P = R * T function bondPrice( uint256 _totalULP, uint256 _totalUBOND, uint256 _targetPrice ) public pure returns (uint256 _priceUBOND) { bytes16 lp = _totalULP.fromUInt(); bytes16 s = _totalUBOND.fromUInt(); bytes16 r = _totalUBOND == 0 ? uint256(1).fromUInt() : lp.div(s); bytes16 t = _targetPrice.fromUInt(); _priceUBOND = r.mul(t).toUInt(); } /// @dev formula ugov multiply /// @param _multiplier , initial ugov min multiplier /// @param _price , current share price /// @return _newMultiplier , new ugov min multiplier /// @notice new_multiplier = multiplier * ( 1.05 / (1 + abs( 1 - price ) ) ) // nM = M * C / A // A = ( 1 + abs( 1 - P))) // 5 >= multiplier >= 0.2 function ugovMultiply(uint256 _multiplier, uint256 _price) public pure returns (uint256 _newMultiplier) { bytes16 m = _multiplier.fromUInt(); bytes16 p = _price.fromUInt(); bytes16 c = uint256(105 * 1e16).fromUInt(); // 1.05 bytes16 u = uint256(1e18).fromUInt(); // 1 bytes16 a = u.add(u.sub(p).abs()); // 1 + abs( 1 - P ) _newMultiplier = m.mul(c).div(a).toUInt(); // nM = M * C / A // 5 >= multiplier >= 0.2 if (_newMultiplier > 5e18 || _newMultiplier < 2e17) _newMultiplier = _multiplier; } }
durationMultiply
function durationMultiply( uint256 _uLP, uint256 _weeks, uint256 _multiplier ) public pure returns (uint256 _shares) { bytes16 unit = uint256(1 ether).fromUInt(); bytes16 d = _weeks.fromUInt(); bytes16 d32 = (d.mul(d).mul(d)).sqrt(); bytes16 m = _multiplier.fromUInt().div(unit); // 0.0001 bytes16 a = _uLP.fromUInt(); _shares = m.mul(d32).mul(a).add(a).toUInt(); }
// D32 = D^3/2 // S = m * D32 * A + A
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 478, 928 ] }
3,277
BondingShareV2
contracts/UbiquityFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityFormulas
contract UbiquityFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; /// @dev formula duration multiply /// @param _uLP , amount of LP tokens /// @param _weeks , mimimun duration of staking period /// @param _multiplier , bonding discount multiplier = 0.0001 /// @return _shares , amount of shares /// @notice _shares = (1 + _multiplier * _weeks^3/2) * _uLP // D32 = D^3/2 // S = m * D32 * A + A function durationMultiply( uint256 _uLP, uint256 _weeks, uint256 _multiplier ) public pure returns (uint256 _shares) { bytes16 unit = uint256(1 ether).fromUInt(); bytes16 d = _weeks.fromUInt(); bytes16 d32 = (d.mul(d).mul(d)).sqrt(); bytes16 m = _multiplier.fromUInt().div(unit); // 0.0001 bytes16 a = _uLP.fromUInt(); _shares = m.mul(d32).mul(a).add(a).toUInt(); } /// @dev formula bonding /// @param _shares , amount of shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uBOND , amount of bonding shares /// @notice UBOND = _shares / _currentShareValue * _targetPrice // newShares = A / V * T function bonding( uint256 _shares, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uBOND) { bytes16 a = _shares.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uBOND = a.div(v).mul(t).toUInt(); } /// @dev formula redeem bonds /// @param _uBOND , amount of bonding shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uLP , amount of LP tokens /// @notice _uLP = _uBOND * _currentShareValue / _targetPrice // _uLP = A * V / T function redeemBonds( uint256 _uBOND, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uLP) { bytes16 a = _uBOND.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula bond price /// @param _totalULP , total LP tokens /// @param _totalUBOND , total bond shares /// @param _targetPrice , target uAD price /// @return _priceUBOND , bond share price /// @notice // IF _totalUBOND = 0 priceBOND = TARGET_PRICE // ELSE priceBOND = totalLP / totalShares * TARGET_PRICE // R = T == 0 ? 1 : LP / S // P = R * T function bondPrice( uint256 _totalULP, uint256 _totalUBOND, uint256 _targetPrice ) public pure returns (uint256 _priceUBOND) { bytes16 lp = _totalULP.fromUInt(); bytes16 s = _totalUBOND.fromUInt(); bytes16 r = _totalUBOND == 0 ? uint256(1).fromUInt() : lp.div(s); bytes16 t = _targetPrice.fromUInt(); _priceUBOND = r.mul(t).toUInt(); } /// @dev formula ugov multiply /// @param _multiplier , initial ugov min multiplier /// @param _price , current share price /// @return _newMultiplier , new ugov min multiplier /// @notice new_multiplier = multiplier * ( 1.05 / (1 + abs( 1 - price ) ) ) // nM = M * C / A // A = ( 1 + abs( 1 - P))) // 5 >= multiplier >= 0.2 function ugovMultiply(uint256 _multiplier, uint256 _price) public pure returns (uint256 _newMultiplier) { bytes16 m = _multiplier.fromUInt(); bytes16 p = _price.fromUInt(); bytes16 c = uint256(105 * 1e16).fromUInt(); // 1.05 bytes16 u = uint256(1e18).fromUInt(); // 1 bytes16 a = u.add(u.sub(p).abs()); // 1 + abs( 1 - P ) _newMultiplier = m.mul(c).div(a).toUInt(); // nM = M * C / A // 5 >= multiplier >= 0.2 if (_newMultiplier > 5e18 || _newMultiplier < 2e17) _newMultiplier = _multiplier; } }
bonding
function bonding( uint256 _shares, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uBOND) { bytes16 a = _shares.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uBOND = a.div(v).mul(t).toUInt(); }
// newShares = A / V * T
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1251, 1593 ] }
3,278
BondingShareV2
contracts/UbiquityFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityFormulas
contract UbiquityFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; /// @dev formula duration multiply /// @param _uLP , amount of LP tokens /// @param _weeks , mimimun duration of staking period /// @param _multiplier , bonding discount multiplier = 0.0001 /// @return _shares , amount of shares /// @notice _shares = (1 + _multiplier * _weeks^3/2) * _uLP // D32 = D^3/2 // S = m * D32 * A + A function durationMultiply( uint256 _uLP, uint256 _weeks, uint256 _multiplier ) public pure returns (uint256 _shares) { bytes16 unit = uint256(1 ether).fromUInt(); bytes16 d = _weeks.fromUInt(); bytes16 d32 = (d.mul(d).mul(d)).sqrt(); bytes16 m = _multiplier.fromUInt().div(unit); // 0.0001 bytes16 a = _uLP.fromUInt(); _shares = m.mul(d32).mul(a).add(a).toUInt(); } /// @dev formula bonding /// @param _shares , amount of shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uBOND , amount of bonding shares /// @notice UBOND = _shares / _currentShareValue * _targetPrice // newShares = A / V * T function bonding( uint256 _shares, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uBOND) { bytes16 a = _shares.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uBOND = a.div(v).mul(t).toUInt(); } /// @dev formula redeem bonds /// @param _uBOND , amount of bonding shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uLP , amount of LP tokens /// @notice _uLP = _uBOND * _currentShareValue / _targetPrice // _uLP = A * V / T function redeemBonds( uint256 _uBOND, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uLP) { bytes16 a = _uBOND.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula bond price /// @param _totalULP , total LP tokens /// @param _totalUBOND , total bond shares /// @param _targetPrice , target uAD price /// @return _priceUBOND , bond share price /// @notice // IF _totalUBOND = 0 priceBOND = TARGET_PRICE // ELSE priceBOND = totalLP / totalShares * TARGET_PRICE // R = T == 0 ? 1 : LP / S // P = R * T function bondPrice( uint256 _totalULP, uint256 _totalUBOND, uint256 _targetPrice ) public pure returns (uint256 _priceUBOND) { bytes16 lp = _totalULP.fromUInt(); bytes16 s = _totalUBOND.fromUInt(); bytes16 r = _totalUBOND == 0 ? uint256(1).fromUInt() : lp.div(s); bytes16 t = _targetPrice.fromUInt(); _priceUBOND = r.mul(t).toUInt(); } /// @dev formula ugov multiply /// @param _multiplier , initial ugov min multiplier /// @param _price , current share price /// @return _newMultiplier , new ugov min multiplier /// @notice new_multiplier = multiplier * ( 1.05 / (1 + abs( 1 - price ) ) ) // nM = M * C / A // A = ( 1 + abs( 1 - P))) // 5 >= multiplier >= 0.2 function ugovMultiply(uint256 _multiplier, uint256 _price) public pure returns (uint256 _newMultiplier) { bytes16 m = _multiplier.fromUInt(); bytes16 p = _price.fromUInt(); bytes16 c = uint256(105 * 1e16).fromUInt(); // 1.05 bytes16 u = uint256(1e18).fromUInt(); // 1 bytes16 a = u.add(u.sub(p).abs()); // 1 + abs( 1 - P ) _newMultiplier = m.mul(c).div(a).toUInt(); // nM = M * C / A // 5 >= multiplier >= 0.2 if (_newMultiplier > 5e18 || _newMultiplier < 2e17) _newMultiplier = _multiplier; } }
redeemBonds
function redeemBonds( uint256 _uBOND, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uLP) { bytes16 a = _uBOND.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); }
// _uLP = A * V / T
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1914, 2254 ] }
3,279
BondingShareV2
contracts/UbiquityFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityFormulas
contract UbiquityFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; /// @dev formula duration multiply /// @param _uLP , amount of LP tokens /// @param _weeks , mimimun duration of staking period /// @param _multiplier , bonding discount multiplier = 0.0001 /// @return _shares , amount of shares /// @notice _shares = (1 + _multiplier * _weeks^3/2) * _uLP // D32 = D^3/2 // S = m * D32 * A + A function durationMultiply( uint256 _uLP, uint256 _weeks, uint256 _multiplier ) public pure returns (uint256 _shares) { bytes16 unit = uint256(1 ether).fromUInt(); bytes16 d = _weeks.fromUInt(); bytes16 d32 = (d.mul(d).mul(d)).sqrt(); bytes16 m = _multiplier.fromUInt().div(unit); // 0.0001 bytes16 a = _uLP.fromUInt(); _shares = m.mul(d32).mul(a).add(a).toUInt(); } /// @dev formula bonding /// @param _shares , amount of shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uBOND , amount of bonding shares /// @notice UBOND = _shares / _currentShareValue * _targetPrice // newShares = A / V * T function bonding( uint256 _shares, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uBOND) { bytes16 a = _shares.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uBOND = a.div(v).mul(t).toUInt(); } /// @dev formula redeem bonds /// @param _uBOND , amount of bonding shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uLP , amount of LP tokens /// @notice _uLP = _uBOND * _currentShareValue / _targetPrice // _uLP = A * V / T function redeemBonds( uint256 _uBOND, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uLP) { bytes16 a = _uBOND.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula bond price /// @param _totalULP , total LP tokens /// @param _totalUBOND , total bond shares /// @param _targetPrice , target uAD price /// @return _priceUBOND , bond share price /// @notice // IF _totalUBOND = 0 priceBOND = TARGET_PRICE // ELSE priceBOND = totalLP / totalShares * TARGET_PRICE // R = T == 0 ? 1 : LP / S // P = R * T function bondPrice( uint256 _totalULP, uint256 _totalUBOND, uint256 _targetPrice ) public pure returns (uint256 _priceUBOND) { bytes16 lp = _totalULP.fromUInt(); bytes16 s = _totalUBOND.fromUInt(); bytes16 r = _totalUBOND == 0 ? uint256(1).fromUInt() : lp.div(s); bytes16 t = _targetPrice.fromUInt(); _priceUBOND = r.mul(t).toUInt(); } /// @dev formula ugov multiply /// @param _multiplier , initial ugov min multiplier /// @param _price , current share price /// @return _newMultiplier , new ugov min multiplier /// @notice new_multiplier = multiplier * ( 1.05 / (1 + abs( 1 - price ) ) ) // nM = M * C / A // A = ( 1 + abs( 1 - P))) // 5 >= multiplier >= 0.2 function ugovMultiply(uint256 _multiplier, uint256 _price) public pure returns (uint256 _newMultiplier) { bytes16 m = _multiplier.fromUInt(); bytes16 p = _price.fromUInt(); bytes16 c = uint256(105 * 1e16).fromUInt(); // 1.05 bytes16 u = uint256(1e18).fromUInt(); // 1 bytes16 a = u.add(u.sub(p).abs()); // 1 + abs( 1 - P ) _newMultiplier = m.mul(c).div(a).toUInt(); // nM = M * C / A // 5 >= multiplier >= 0.2 if (_newMultiplier > 5e18 || _newMultiplier < 2e17) _newMultiplier = _multiplier; } }
bondPrice
function bondPrice( uint256 _totalULP, uint256 _totalUBOND, uint256 _targetPrice ) public pure returns (uint256 _priceUBOND) { bytes16 lp = _totalULP.fromUInt(); bytes16 s = _totalUBOND.fromUInt(); bytes16 r = _totalUBOND == 0 ? uint256(1).fromUInt() : lp.div(s); bytes16 t = _targetPrice.fromUInt(); _priceUBOND = r.mul(t).toUInt(); }
// IF _totalUBOND = 0 priceBOND = TARGET_PRICE // ELSE priceBOND = totalLP / totalShares * TARGET_PRICE // R = T == 0 ? 1 : LP / S // P = R * T
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2665, 3077 ] }
3,280
BondingShareV2
contracts/UbiquityFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityFormulas
contract UbiquityFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; /// @dev formula duration multiply /// @param _uLP , amount of LP tokens /// @param _weeks , mimimun duration of staking period /// @param _multiplier , bonding discount multiplier = 0.0001 /// @return _shares , amount of shares /// @notice _shares = (1 + _multiplier * _weeks^3/2) * _uLP // D32 = D^3/2 // S = m * D32 * A + A function durationMultiply( uint256 _uLP, uint256 _weeks, uint256 _multiplier ) public pure returns (uint256 _shares) { bytes16 unit = uint256(1 ether).fromUInt(); bytes16 d = _weeks.fromUInt(); bytes16 d32 = (d.mul(d).mul(d)).sqrt(); bytes16 m = _multiplier.fromUInt().div(unit); // 0.0001 bytes16 a = _uLP.fromUInt(); _shares = m.mul(d32).mul(a).add(a).toUInt(); } /// @dev formula bonding /// @param _shares , amount of shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uBOND , amount of bonding shares /// @notice UBOND = _shares / _currentShareValue * _targetPrice // newShares = A / V * T function bonding( uint256 _shares, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uBOND) { bytes16 a = _shares.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uBOND = a.div(v).mul(t).toUInt(); } /// @dev formula redeem bonds /// @param _uBOND , amount of bonding shares /// @param _currentShareValue , current share value /// @param _targetPrice , target uAD price /// @return _uLP , amount of LP tokens /// @notice _uLP = _uBOND * _currentShareValue / _targetPrice // _uLP = A * V / T function redeemBonds( uint256 _uBOND, uint256 _currentShareValue, uint256 _targetPrice ) public pure returns (uint256 _uLP) { bytes16 a = _uBOND.fromUInt(); bytes16 v = _currentShareValue.fromUInt(); bytes16 t = _targetPrice.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula bond price /// @param _totalULP , total LP tokens /// @param _totalUBOND , total bond shares /// @param _targetPrice , target uAD price /// @return _priceUBOND , bond share price /// @notice // IF _totalUBOND = 0 priceBOND = TARGET_PRICE // ELSE priceBOND = totalLP / totalShares * TARGET_PRICE // R = T == 0 ? 1 : LP / S // P = R * T function bondPrice( uint256 _totalULP, uint256 _totalUBOND, uint256 _targetPrice ) public pure returns (uint256 _priceUBOND) { bytes16 lp = _totalULP.fromUInt(); bytes16 s = _totalUBOND.fromUInt(); bytes16 r = _totalUBOND == 0 ? uint256(1).fromUInt() : lp.div(s); bytes16 t = _targetPrice.fromUInt(); _priceUBOND = r.mul(t).toUInt(); } /// @dev formula ugov multiply /// @param _multiplier , initial ugov min multiplier /// @param _price , current share price /// @return _newMultiplier , new ugov min multiplier /// @notice new_multiplier = multiplier * ( 1.05 / (1 + abs( 1 - price ) ) ) // nM = M * C / A // A = ( 1 + abs( 1 - P))) // 5 >= multiplier >= 0.2 function ugovMultiply(uint256 _multiplier, uint256 _price) public pure returns (uint256 _newMultiplier) { bytes16 m = _multiplier.fromUInt(); bytes16 p = _price.fromUInt(); bytes16 c = uint256(105 * 1e16).fromUInt(); // 1.05 bytes16 u = uint256(1e18).fromUInt(); // 1 bytes16 a = u.add(u.sub(p).abs()); // 1 + abs( 1 - P ) _newMultiplier = m.mul(c).div(a).toUInt(); // nM = M * C / A // 5 >= multiplier >= 0.2 if (_newMultiplier > 5e18 || _newMultiplier < 2e17) _newMultiplier = _multiplier; } }
ugovMultiply
function ugovMultiply(uint256 _multiplier, uint256 _price) public pure returns (uint256 _newMultiplier) { bytes16 m = _multiplier.fromUInt(); bytes16 p = _price.fromUInt(); bytes16 c = uint256(105 * 1e16).fromUInt(); // 1.05 bytes16 u = uint256(1e18).fromUInt(); // 1 bytes16 a = u.add(u.sub(p).abs()); // 1 + abs( 1 - P ) _newMultiplier = m.mul(c).div(a).toUInt(); // nM = M * C / A // 5 >= multiplier >= 0.2 if (_newMultiplier > 5e18 || _newMultiplier < 2e17) _newMultiplier = _multiplier; }
// nM = M * C / A // A = ( 1 + abs( 1 - P))) // 5 >= multiplier >= 0.2
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3436, 4043 ] }
3,281
YearnBridgeSwapper
contracts/ZkSyncBridgeSwapper.sol
0xdea6888997d4843143d20ba2c85f0d3a6fbecccd
Solidity
ZkSyncBridgeSwapper
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper { // The owner of the contract address public owner; // The max slippage accepted for swapping. Defaults to 1% with 6 decimals. uint256 public slippagePercent = 1e6; // The ZkSync bridge contract address public immutable zkSync; // The L2 market maker account address public immutable l2Account; address constant internal ETH_TOKEN = address(0); event OwnerChanged(address _owner, address _newOwner); event SlippageChanged(uint256 _slippagePercent); modifier onlyOwner { require(msg.sender == owner, "unauthorised"); _; } constructor(address _zkSync, address _l2Account) { zkSync = _zkSync; l2Account = _l2Account; owner = msg.sender; } function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "invalid input"); owner = _newOwner; emit OwnerChanged(owner, _newOwner); } function changeSlippage(uint256 _slippagePercent) external onlyOwner { require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage"); slippagePercent = _slippagePercent; emit SlippageChanged(slippagePercent); } /** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */ function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } } /** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */ function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } } /** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */ function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); } /** * @dev fallback method to make sure we can receive ETH */ receive() external payable { } /** * @dev Returns the minimum accepted out amount. */ function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } }
transferFromZkSync
function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } }
/** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */
NatSpecMultiLine
v0.8.3+commit.8d00100c
{ "func_code_index": [ 1437, 1736 ] }
3,282
YearnBridgeSwapper
contracts/ZkSyncBridgeSwapper.sol
0xdea6888997d4843143d20ba2c85f0d3a6fbecccd
Solidity
ZkSyncBridgeSwapper
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper { // The owner of the contract address public owner; // The max slippage accepted for swapping. Defaults to 1% with 6 decimals. uint256 public slippagePercent = 1e6; // The ZkSync bridge contract address public immutable zkSync; // The L2 market maker account address public immutable l2Account; address constant internal ETH_TOKEN = address(0); event OwnerChanged(address _owner, address _newOwner); event SlippageChanged(uint256 _slippagePercent); modifier onlyOwner { require(msg.sender == owner, "unauthorised"); _; } constructor(address _zkSync, address _l2Account) { zkSync = _zkSync; l2Account = _l2Account; owner = msg.sender; } function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "invalid input"); owner = _newOwner; emit OwnerChanged(owner, _newOwner); } function changeSlippage(uint256 _slippagePercent) external onlyOwner { require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage"); slippagePercent = _slippagePercent; emit SlippageChanged(slippagePercent); } /** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */ function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } } /** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */ function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } } /** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */ function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); } /** * @dev fallback method to make sure we can receive ETH */ receive() external payable { } /** * @dev Returns the minimum accepted out amount. */ function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } }
transferToZkSync
function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } }
/** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */
NatSpecMultiLine
v0.8.3+commit.8d00100c
{ "func_code_index": [ 1909, 2458 ] }
3,283
YearnBridgeSwapper
contracts/ZkSyncBridgeSwapper.sol
0xdea6888997d4843143d20ba2c85f0d3a6fbecccd
Solidity
ZkSyncBridgeSwapper
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper { // The owner of the contract address public owner; // The max slippage accepted for swapping. Defaults to 1% with 6 decimals. uint256 public slippagePercent = 1e6; // The ZkSync bridge contract address public immutable zkSync; // The L2 market maker account address public immutable l2Account; address constant internal ETH_TOKEN = address(0); event OwnerChanged(address _owner, address _newOwner); event SlippageChanged(uint256 _slippagePercent); modifier onlyOwner { require(msg.sender == owner, "unauthorised"); _; } constructor(address _zkSync, address _l2Account) { zkSync = _zkSync; l2Account = _l2Account; owner = msg.sender; } function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "invalid input"); owner = _newOwner; emit OwnerChanged(owner, _newOwner); } function changeSlippage(uint256 _slippagePercent) external onlyOwner { require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage"); slippagePercent = _slippagePercent; emit SlippageChanged(slippagePercent); } /** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */ function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } } /** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */ function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } } /** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */ function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); } /** * @dev fallback method to make sure we can receive ETH */ receive() external payable { } /** * @dev Returns the minimum accepted out amount. */ function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } }
recoverToken
function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); }
/** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */
NatSpecMultiLine
v0.8.3+commit.8d00100c
{ "func_code_index": [ 2613, 3057 ] }
3,284
YearnBridgeSwapper
contracts/ZkSyncBridgeSwapper.sol
0xdea6888997d4843143d20ba2c85f0d3a6fbecccd
Solidity
ZkSyncBridgeSwapper
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper { // The owner of the contract address public owner; // The max slippage accepted for swapping. Defaults to 1% with 6 decimals. uint256 public slippagePercent = 1e6; // The ZkSync bridge contract address public immutable zkSync; // The L2 market maker account address public immutable l2Account; address constant internal ETH_TOKEN = address(0); event OwnerChanged(address _owner, address _newOwner); event SlippageChanged(uint256 _slippagePercent); modifier onlyOwner { require(msg.sender == owner, "unauthorised"); _; } constructor(address _zkSync, address _l2Account) { zkSync = _zkSync; l2Account = _l2Account; owner = msg.sender; } function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "invalid input"); owner = _newOwner; emit OwnerChanged(owner, _newOwner); } function changeSlippage(uint256 _slippagePercent) external onlyOwner { require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage"); slippagePercent = _slippagePercent; emit SlippageChanged(slippagePercent); } /** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */ function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } } /** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */ function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } } /** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */ function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); } /** * @dev fallback method to make sure we can receive ETH */ receive() external payable { } /** * @dev Returns the minimum accepted out amount. */ function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } }
/** * @dev fallback method to make sure we can receive ETH */
NatSpecMultiLine
v0.8.3+commit.8d00100c
{ "func_code_index": [ 3135, 3182 ] }
3,285
YearnBridgeSwapper
contracts/ZkSyncBridgeSwapper.sol
0xdea6888997d4843143d20ba2c85f0d3a6fbecccd
Solidity
ZkSyncBridgeSwapper
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper { // The owner of the contract address public owner; // The max slippage accepted for swapping. Defaults to 1% with 6 decimals. uint256 public slippagePercent = 1e6; // The ZkSync bridge contract address public immutable zkSync; // The L2 market maker account address public immutable l2Account; address constant internal ETH_TOKEN = address(0); event OwnerChanged(address _owner, address _newOwner); event SlippageChanged(uint256 _slippagePercent); modifier onlyOwner { require(msg.sender == owner, "unauthorised"); _; } constructor(address _zkSync, address _l2Account) { zkSync = _zkSync; l2Account = _l2Account; owner = msg.sender; } function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "invalid input"); owner = _newOwner; emit OwnerChanged(owner, _newOwner); } function changeSlippage(uint256 _slippagePercent) external onlyOwner { require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage"); slippagePercent = _slippagePercent; emit SlippageChanged(slippagePercent); } /** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */ function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } } /** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */ function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } } /** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */ function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); } /** * @dev fallback method to make sure we can receive ETH */ receive() external payable { } /** * @dev Returns the minimum accepted out amount. */ function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } }
getMinAmountOut
function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; }
/** * @dev Returns the minimum accepted out amount. */
NatSpecMultiLine
v0.8.3+commit.8d00100c
{ "func_code_index": [ 3253, 3402 ] }
3,286
YearnBridgeSwapper
contracts/ZkSyncBridgeSwapper.sol
0xdea6888997d4843143d20ba2c85f0d3a6fbecccd
Solidity
ZkSyncBridgeSwapper
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper { // The owner of the contract address public owner; // The max slippage accepted for swapping. Defaults to 1% with 6 decimals. uint256 public slippagePercent = 1e6; // The ZkSync bridge contract address public immutable zkSync; // The L2 market maker account address public immutable l2Account; address constant internal ETH_TOKEN = address(0); event OwnerChanged(address _owner, address _newOwner); event SlippageChanged(uint256 _slippagePercent); modifier onlyOwner { require(msg.sender == owner, "unauthorised"); _; } constructor(address _zkSync, address _l2Account) { zkSync = _zkSync; l2Account = _l2Account; owner = msg.sender; } function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "invalid input"); owner = _newOwner; emit OwnerChanged(owner, _newOwner); } function changeSlippage(uint256 _slippagePercent) external onlyOwner { require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage"); slippagePercent = _slippagePercent; emit SlippageChanged(slippagePercent); } /** * @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable. * @param _token The token to withdraw. */ function transferFromZkSync(address _token) internal { uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token); if (pendingBalance > 0) { IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance); } } /** * @dev Deposit the ETH or ERC20 token to zkSync. * @param _outputToken The token that was given. * @param _amountOut The amount of given token. */ function transferToZkSync(address _outputToken, uint256 _amountOut) internal { if (_outputToken == ETH_TOKEN) { // deposit Eth to L2 bridge IZkSync(zkSync).depositETH{value: _amountOut}(l2Account); } else { // approve the zkSync bridge to take the output token IERC20(_outputToken).approve(zkSync, _amountOut); // deposit the output token to the L2 bridge IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account); } } /** * @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error. * @param _token The token to recover. */ function recoverToken(address _token) external returns (uint256 balance) { bool success; if (_token == ETH_TOKEN) { balance = address(this).balance; (success, ) = owner.call{value: balance}(""); } else { balance = IERC20(_token).balanceOf(address(this)); success = IERC20(_token).transfer(owner, balance); } require(success, "failed to recover"); } /** * @dev fallback method to make sure we can receive ETH */ receive() external payable { } /** * @dev Returns the minimum accepted out amount. */ function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) { return _amountIn * (100e6 - slippagePercent) / 100e6; } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } }
toUint104
function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); }
/** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). */
NatSpecMultiLine
v0.8.3+commit.8d00100c
{ "func_code_index": [ 3556, 3752 ] }
3,287
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 966, 1087 ] }
3,288
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 1307, 1436 ] }
3,289
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 1780, 2062 ] }
3,290
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 2570, 2783 ] }
3,291
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 3314, 3677 ] }
3,292
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 3960, 4116 ] }
3,293
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 4471, 4793 ] }
3,294
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
function () public payable { revert(); }
// ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 4985, 5044 ] }
3,295
Brcoin
Brcoin.sol
0xfdf03c2662553d71e473d118ebcac403480c3119
Solidity
Brcoin
contract Brcoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRC"; name = "Brcoin"; decimals = 8; _totalSupply = 1000000000000000000; balances[0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3] = _totalSupply; emit Transfer(address(0), 0xB89222A515951Db32C34d7Cbf93E9f4A7Cf134F3, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
None
bzzr://7c1b91140415b79412c029fdd1a8e00bc1110b245b272d52137a7d8d3747a4de
{ "func_code_index": [ 5277, 5466 ] }
3,296
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
paybackDebt
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } }
/// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 1262, 2052 ] }
3,297
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
getFee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } }
/// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 2395, 3805 ] }
3,298
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
getGasCost
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } }
/// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 4132, 5124 ] }
3,299
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
enterMarket
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); }
/// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 5354, 5644 ] }
3,300
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
approveCToken
function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } }
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 5851, 6052 ] }
3,301
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
getUnderlyingAddr
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } }
/// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 6220, 6479 ] }
3,302
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
getUserAddress
function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); }
/// @notice Returns the owner of the DSProxy that called the contract
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 6555, 6712 ] }
3,303
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
getMaxCollateral
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues }
/// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 7049, 8082 ] }
3,304
AaveMonitorV2
contracts/compound/helpers/CompoundSaverHelper.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
CompoundSaverHelper
contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } }
/// @title Utlity functions for Compound contracts
NatSpecSingleLine
getMaxBorrow
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues }
/// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 8410, 8998 ] }
3,305
BondingShareV2
contracts/interfaces/IMasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
IMasterChefV2
interface IMasterChefV2 { struct BondingShareInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accuGOVPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 amount, uint256 bondingShareID); event Withdraw( address indexed user, uint256 amount, uint256 bondingShareID ); function deposit( address sender, uint256 amount, uint256 bondingShareID ) external; // Withdraw LP tokens from MasterChef. function withdraw( address sender, uint256 amount, uint256 bondingShareID ) external; // Info about a bondinh share function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory); // Total amount of shares function totalShares() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingUGOV(address _user) external view returns (uint256); }
withdraw
function withdraw( address sender, uint256 amount, uint256 bondingShareID ) external;
// Withdraw LP tokens from MasterChef.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 756, 873 ] }
3,306