Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SafeERC20: Add safe total supply #543

Merged
merged 2 commits into from
Jul 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions contracts/common/SafeERC20.sol
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,17 @@ library SafeERC20 {

return allowance;
}

/**
* @dev Static call into ERC20.totalSupply().
* Reverts if the call fails for some reason (should never fail).
*/
function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);

(bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);

return totalSupply;
}
}
4 changes: 4 additions & 0 deletions contracts/test/mocks/lib/token/SafeERC20Mock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,8 @@ contract SafeERC20Mock {
function balanceOf(ERC20 token, address owner) external view returns (uint256) {
return token.staticBalanceOf(owner);
}

function totalSupply(ERC20 token) external view returns (uint256) {
return token.staticTotalSupply();
}
}
6 changes: 6 additions & 0 deletions test/contracts/common/safe_erc20.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@ contract('SafeERC20', ([owner, receiver]) => {
assert.equal(balance, initialBalance, 'Mock should return correct balance')
assert.equal((await tokenMock.balanceOf(owner)).valueOf(), balance, "Mock should match token contract's balance")
})

it('gives correct value with static totalSupply', async () => {
const totalSupply = (await safeERC20Mock.totalSupply(tokenMock.address)).valueOf()
assert.equal(totalSupply, initialBalance, 'Mock should return correct total supply')
assert.equal((await tokenMock.totalSupply()).valueOf(), totalSupply, "Mock should match token contract's total supply")
})
})
}
})