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

fix(contracts): Frontrun Permit in GasSwap #1184

Closed
wants to merge 10 commits into from
40 changes: 40 additions & 0 deletions contracts/integration-test/GasSwap.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,46 @@ describe("GasSwap.spec", async () => {
).to.revertedWith("insufficient output amount");
});

it("should succeed, when attacker frontrun permit", async () => {
const amountIn = ethers.utils.parseEther("1");
const amountOut = ethers.utils.parseEther("2");
await token.mint(signer.address, amountIn);
await deployer.sendTransaction({ to: target.address, value: amountOut });
const signature = await permit(amountIn);

await token.permit(
signer.address,
swap.address,
amountIn,
constants.MaxUint256,
signature.v,
signature.r,
signature.s
);

await target.setToken(token.address);
await target.setAmountIn(amountIn);

await swap.updateApprovedTarget(target.address, true);
await expect(
swap.connect(signer).swap(
{
token: token.address,
value: amountIn,
deadline: constants.MaxUint256,
r: signature.r,
s: signature.s,
v: signature.v,
},
{
target: target.address,
data: "0x8119c065",
minOutput: 0,
}
)
);
});

for (const refundRatio of ["0", "1", "5"]) {
for (const feeRatio of ["0", "5", "50"]) {
it(`should succeed, when swap by signer directly, with feeRatio[${feeRatio}%] refundRatio[${refundRatio}%]`, async () => {
Expand Down
23 changes: 13 additions & 10 deletions contracts/src/gas-swap/GasSwap.sol
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {Context} from "@openzeppelin/contracts/utils/Context.sol";

contract GasSwap is ERC2771Context, Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeERC20 for IERC20Permit;

/**********
* Events *
Expand Down Expand Up @@ -92,15 +91,19 @@ contract GasSwap is ERC2771Context, Ownable, ReentrancyGuard {
address _sender = _msgSender();

// do permit
IERC20Permit(_permit.token).safePermit(
_sender,
address(this),
_permit.value,
_permit.deadline,
_permit.v,
_permit.r,
_permit.s
);
try
IERC20Permit(_permit.token).permit(
_sender,
address(this),
_permit.value,
_permit.deadline,
_permit.v,
_permit.r,
_permit.s
)
{} catch {
require(IERC20(_permit.token).allowance(_sender, address(this)) >= _permit.value, "Permit failed");
}

// record token balance in this contract
uint256 _balance = IERC20(_permit.token).balanceOf(address(this));
Expand Down
Loading