Skip to content

Commit

Permalink
SafeERC20: Add safe total supply (#543)
Browse files Browse the repository at this point in the history
  • Loading branch information
facuspagnuolo authored and sohkai committed Jul 15, 2019
1 parent fbf0fad commit 4feb97a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
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")
})
})
}
})

0 comments on commit 4feb97a

Please sign in to comment.