Skip to content

Commit

Permalink
✨ STL: totalSupply (#1212)
Browse files Browse the repository at this point in the history
  • Loading branch information
z0r0z authored Dec 6, 2024
1 parent d23e231 commit 3f2f534
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/utils/SafeTransferLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ library SafeTransferLib {
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();

/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();

/// @dev The Permit2 operation has failed.
error Permit2Failed();

Expand Down Expand Up @@ -396,6 +399,22 @@ library SafeTransferLib {
}
}

/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}

/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
Expand Down
12 changes: 12 additions & 0 deletions test/SafeTransferLib.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -1091,4 +1091,16 @@ contract SafeTransferLibTest is SoladyTest {
t.s
);
}

function testTotalSupplyQuery() public {
uint256 totalSupplyBefore = this.totalSupplyQuery(address(erc20));
erc20.burn(address(this), 123);
assertEq(this.totalSupplyQuery(address(erc20)), totalSupplyBefore - 123);
vm.expectRevert(SafeTransferLib.TotalSupplyQueryFailed.selector);
this.totalSupplyQuery(address(0));
}

function totalSupplyQuery(address token) public view returns (uint256) {
return SafeTransferLib.totalSupply(token);
}
}

0 comments on commit 3f2f534

Please sign in to comment.