Verified contractExactISC
Accounting
Address0xe9ccf534fb8f19d579640094d08962fbfac81bec
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.36
- Same code
Only this contract
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- No
- License
- ISC
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,427,101
- Creation transaction
- 0x949c21f108…63740d0308
8 files
- contracts/hub/Accounting.solmain6.51 KB
- contracts/common/types/AccountId.sol351 B
- contracts/common/types/PoolId.sol792 B
- contracts/hub/interfaces/IAccounting.sol4.04 KB
- contracts/misc/Auth.sol866 B
- contracts/misc/interfaces/IAuth.sol526 B
- contracts/misc/libraries/MathLib.sol8.17 KB
- contracts/misc/libraries/TransientStorageLib.sol1.51 KB
contracts/hub/Accounting.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {Auth} from "contracts/misc/Auth.sol";
import {TransientStorageLib} from "contracts/misc/libraries/TransientStorageLib.sol";
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AccountId} from "contracts/common/types/AccountId.sol";
import {IAccounting, JournalEntry} from "contracts/hub/interfaces/IAccounting.sol";
/// @notice In a transaction there can be multiple journal entries for different pools,
/// which can be interleaved. We want entries for the same pool to share the same journal ID.
/// So we're keeping a journal ID per pool in transient storage.
library TransientJournal {
function journalId(PoolId poolId) internal view returns (uint256) {
return TransientStorageLib.tloadUint256(keccak256(abi.encode("journalId", poolId)));
}
function setJournalId(PoolId poolId, uint256 value) internal {
TransientStorageLib.tstore(keccak256(abi.encode("journalId", poolId)), value);
}
}
/// @title Accounting
/// @notice Double-entry bookkeeping system.
/// @dev To add entries, a specific pool needs to be unlocked.
/// When locking, the debited and credited amounts need to match.
contract Accounting is Auth, IAccounting {
mapping(PoolId => mapping(AccountId => Account)) public accounts;
uint128 public transient debited;
uint128 public transient credited;
PoolId internal transient _currentPoolId;
mapping(PoolId => uint64) internal _poolJournalIdCounter;
constructor(address deployer) Auth(deployer) {}
//----------------------------------------------------------------------------------------------
// Lock/unlock
//----------------------------------------------------------------------------------------------
/// @inheritdoc IAccounting
function unlock(PoolId poolId) external auth {
require(PoolId.unwrap(_currentPoolId) == 0, AccountingAlreadyUnlocked());
debited = 0;
credited = 0;
_currentPoolId = poolId;
if (TransientJournal.journalId(poolId) == 0) {
TransientJournal.setJournalId(poolId, _generateJournalId(poolId));
}
emit StartJournalId(poolId, TransientJournal.journalId(poolId));
}
/// @inheritdoc IAccounting
function lock() external auth {
require(debited == credited, Unbalanced());
emit EndJournalId(_currentPoolId, TransientJournal.journalId(_currentPoolId));
_currentPoolId = PoolId.wrap(0);
}
//----------------------------------------------------------------------------------------------
// Account creation & metadata
//----------------------------------------------------------------------------------------------
/// @inheritdoc IAccounting
function createAccount(PoolId poolId, AccountId account, bool isDebitNormal) external auth {
require(accounts[poolId][account].lastUpdated == 0, AccountExists());
accounts[poolId][account] = Account(0, 0, isDebitNormal, uint64(block.timestamp), "");
emit CreateAccount(poolId, account, isDebitNormal);
}
/// @inheritdoc IAccounting
function setAccountMetadata(PoolId poolId, AccountId account, bytes calldata metadata) external auth {
require(accounts[poolId][account].lastUpdated != 0, AccountDoesNotExist());
accounts[poolId][account].metadata = metadata;
emit SetAccountMetadata(poolId, account, metadata);
}
//----------------------------------------------------------------------------------------------
// Account updates
//----------------------------------------------------------------------------------------------
/// @inheritdoc IAccounting
function addDebit(AccountId account, uint128 value) public auth {
require(!_currentPoolId.isNull(), AccountingLocked());
Account storage acc = accounts[_currentPoolId][account];
require(acc.lastUpdated != 0, AccountDoesNotExist());
acc.totalDebit += value;
debited += value;
acc.lastUpdated = uint64(block.timestamp);
emit Debit(_currentPoolId, account, value);
}
/// @inheritdoc IAccounting
function addCredit(AccountId account, uint128 value) public auth {
require(!_currentPoolId.isNull(), AccountingLocked());
Account storage acc = accounts[_currentPoolId][account];
require(acc.lastUpdated != 0, AccountDoesNotExist());
acc.totalCredit += value;
credited += value;
acc.lastUpdated = uint64(block.timestamp);
emit Credit(_currentPoolId, account, value);
}
/// @inheritdoc IAccounting
function addJournal(JournalEntry[] memory debits, JournalEntry[] memory credits) external auth {
for (uint256 i; i < debits.length; i++) {
addDebit(debits[i].accountId, debits[i].value);
}
for (uint256 i; i < credits.length; i++) {
addCredit(credits[i].accountId, credits[i].value);
}
}
//----------------------------------------------------------------------------------------------
// View methods
//----------------------------------------------------------------------------------------------
/// @inheritdoc IAccounting
function accountValue(PoolId poolId, AccountId account) external view returns (bool, /* isPositive */ uint128) {
Account storage acc = accounts[poolId][account];
require(acc.lastUpdated != 0, AccountDoesNotExist());
if (acc.isDebitNormal) {
// For debit-normal accounts: Value = Total Debit - Total Credit
if (acc.totalDebit >= acc.totalCredit) {
return (true, acc.totalDebit - acc.totalCredit);
} else {
return (false, acc.totalCredit - acc.totalDebit);
}
} else {
// For credit-normal accounts: Value = Total Credit - Total Debit
if (acc.totalCredit >= acc.totalDebit) {
return (true, acc.totalCredit - acc.totalDebit);
} else {
return (false, acc.totalDebit - acc.totalCredit);
}
}
}
/// @inheritdoc IAccounting
function exists(PoolId poolId, AccountId account) external view returns (bool) {
return accounts[poolId][account].lastUpdated != 0;
}
function _generateJournalId(PoolId poolId) internal returns (uint256) {
return uint256((uint256(poolId.raw()) << 128) | ++_poolJournalIdCounter[poolId]);
}
}
contracts/common/types/AccountId.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
type AccountId is uint32;
function raw(AccountId accountId_) pure returns (uint32) {
return AccountId.unwrap(accountId_);
}
function neq(AccountId a, AccountId b) pure returns (bool) {
return AccountId.unwrap(a) != AccountId.unwrap(b);
}
using {raw, neq as !=} for AccountId global;
contracts/common/types/PoolId.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {MathLib} from "contracts/misc/libraries/MathLib.sol";
using MathLib for uint256;
type PoolId is uint64;
function tokenId(PoolId poolId) pure returns (uint16) {
return uint16(PoolId.unwrap(poolId) >> 48);
}
function newPoolId(uint16 tokenId_, uint48 localPoolId) pure returns (PoolId) {
return PoolId.wrap((uint64(tokenId_) << 48) | uint64(localPoolId));
}
function isNull(PoolId poolId) pure returns (bool) {
return PoolId.unwrap(poolId) == 0;
}
function isEqual(PoolId a, PoolId b) pure returns (bool) {
return PoolId.unwrap(a) == PoolId.unwrap(b);
}
function raw(PoolId poolId) pure returns (uint64) {
return PoolId.unwrap(poolId);
}
using {tokenId, isNull, raw, isEqual as ==} for PoolId global;
contracts/hub/interfaces/IAccounting.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {PoolId} from "contracts/common/types/PoolId.sol";
import {AccountId} from "contracts/common/types/AccountId.sol";
struct JournalEntry {
uint128 value;
AccountId accountId;
}
interface IAccounting {
/// @notice Emitted when a an entry is done
event Credit(PoolId indexed poolId, AccountId indexed account, uint128 value);
event Debit(PoolId indexed poolId, AccountId indexed account, uint128 value);
/// @notice Emitted at the beginning and end of a journal entry
event StartJournalId(PoolId indexed poolId, uint256 journalId);
event EndJournalId(PoolId indexed poolId, uint256 journalId);
/// @notice Emitted when a new account is created
event CreateAccount(PoolId indexed poolId, AccountId indexed account, bool isDebitNormal);
/// @notice Emitted when metadata is set for an account
event SetAccountMetadata(PoolId indexed poolId, AccountId indexed account, bytes metadata);
/// @notice Dispatched when the pool is already unlocked.
error AccountingAlreadyUnlocked();
/// @notice Dispatched when the pool is not unlocked to interact with.
error AccountingLocked();
/// @notice Dispatched when the debit and credit side do not match at the end of a transaction.
error Unbalanced();
/// @notice Dispatched when trying to create an account that already exists.
error AccountExists();
/// @notice Dispatched when trying debit or credit an account that doesn't exists.
error AccountDoesNotExist();
/// @notice Represents an account
struct Account {
uint128 totalDebit;
uint128 totalCredit;
bool isDebitNormal;
uint64 lastUpdated;
bytes metadata;
}
/// @notice Debits an account. Increase the value of debit-normal accounts, decrease for credit-normal ones.
/// @param account The account to debit
/// @param value Amount being debited
function addDebit(AccountId account, uint128 value) external;
/// @notice Credits an account. Decrease the value of debit-normal accounts, increase for credit-normal ones.
/// @param account The account to credit
/// @param value Amount being credited
function addCredit(AccountId account, uint128 value) external;
/// @notice Apply addDebit and addCredit to each journal entry
function addJournal(JournalEntry[] memory debits, JournalEntry[] memory credits) external;
/// @notice Unlocks a pool for journal entries
/// @param poolId The pool to unlock
function unlock(PoolId poolId) external;
/// @notice Closes the transaction and checks if the entries are balanced.
function lock() external;
/// @notice Creates an account.
/// @param poolId The pool the account belongs to
/// @param account The account to create
/// @param isDebitNormal Whether the account is debit-normal or credit-normal
function createAccount(PoolId poolId, AccountId account, bool isDebitNormal) external;
/// @notice Sets metadata associated to an existent account.
/// @param poolId The pool the account belongs to
/// @param account The account to set metadata for
/// @param metadata The metadata to set
function setAccountMetadata(PoolId poolId, AccountId account, bytes calldata metadata) external;
/// @notice Returns the value of an account
/// @param poolId The pool the account belongs to
/// @param account The account to get the value of
/// @return isPositive Indicates whether value is a positive or negative value
/// @return value The value of the account
function accountValue(PoolId poolId, AccountId account) external view returns (bool isPositive, uint128 value);
/// @notice Returns whether an account exists
/// @param poolId The pool the account belongs to
/// @param account The account to check
/// @return True if the account exists, false otherwise
function exists(PoolId poolId, AccountId account) external view returns (bool);
}
contracts/misc/Auth.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
import {IAuth} from "contracts/misc/interfaces/IAuth.sol";
/// @title Auth
/// @notice Simple authentication pattern
/// @author Based on code from https://github.com/makerdao/dss
abstract contract Auth is IAuth {
/// @inheritdoc IAuth
mapping(address => uint256) public wards;
constructor(address initialWard) {
wards[initialWard] = 1;
emit Rely(initialWard);
}
/// @dev Check if the msg.sender has permissions
modifier auth() {
require(wards[msg.sender] == 1, NotAuthorized());
_;
}
/// @inheritdoc IAuth
function rely(address user) public auth {
wards[user] = 1;
emit Rely(user);
}
/// @inheritdoc IAuth
function deny(address user) public auth {
wards[user] = 0;
emit Deny(user);
}
}
contracts/misc/interfaces/IAuth.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
interface IAuth {
event Rely(address indexed user);
event Deny(address indexed user);
error NotAuthorized();
/// @notice Returns whether the target is a ward (has admin access)
function wards(address target) external view returns (uint256);
/// @notice Make user a ward (give them admin access)
function rely(address user) external;
/// @notice Remove user as a ward (remove admin access)
function deny(address user) external;
}
contracts/misc/libraries/MathLib.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
library MathLib {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
error MulDiv_Overflow();
error Uint8_Overflow();
error Uint32_Overflow();
error Uint64_Overflow();
error Uint128_Overflow();
error Int128_Overflow();
uint256 public constant One27 = 10 ** 27;
/// @notice Returns x^n with rounding precision of base
///
/// @dev Source: https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/jug.sol#L62
///
/// @param x The base value which should be exponentiated
/// @param n The exponent
/// @param base The scaling base, typically used for fix-point calculations
function rpow(uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 { z := base }
default { z := 0 }
}
default {
switch mod(n, 2)
case 0 { z := base }
default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n, 2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0, 0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0, 0) }
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0, 0) }
z := div(zxRound, base)
}
}
}
}
}
/// @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
/// denominator == 0
/// @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
/// with further edits by Uniswap Labs also under MIT license.
// slither-disable-start divide-before-multiply
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, MulDiv_Overflow());
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
// slither-disable-end divide-before-multiply
/// @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/// @notice Safe type conversion from uint256 to uint8.
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, Uint8_Overflow());
return uint8(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, Uint32_Overflow());
return uint32(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, Uint64_Overflow());
return uint64(value);
}
/// @notice Safe type conversion from uint256 to uint128.
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, Uint128_Overflow());
return uint128(value);
}
/// @notice Returns the smallest of two numbers.
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
/// @notice Returns the largest of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}
contracts/misc/libraries/TransientStorageLib.sol
// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;
/// @title TransientStorageLib
library TransientStorageLib {
function tstore(bytes32 slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
function tstore(bytes32 slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
function tstore(bytes32 slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
function tstore(bytes32 slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
function tloadAddress(bytes32 slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
function tloadUint128(bytes32 slot) internal view returns (uint128 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
function tloadUint256(bytes32 slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
function tloadBytes32(bytes32 slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
function tloadBool(bytes32 slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": false
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.