Migrate metatx tests to ethers.js (#4737)

Co-authored-by: ernestognw <ernestognw@gmail.com>
This commit is contained in:
Hadrien Croubois
2023-11-23 03:24:21 +01:00
committed by GitHub
parent 6bc1173c8e
commit e473bcf859
6 changed files with 408 additions and 485 deletions

View File

@ -4,10 +4,10 @@ const { impersonateAccount, setBalance } = require('@nomicfoundation/hardhat-net
// Hardhat default balance // Hardhat default balance
const DEFAULT_BALANCE = 10000n * ethers.WeiPerEther; const DEFAULT_BALANCE = 10000n * ethers.WeiPerEther;
async function impersonate(account, balance = DEFAULT_BALANCE) { const impersonate = (account, balance = DEFAULT_BALANCE) =>
await impersonateAccount(account); impersonateAccount(account)
await setBalance(account, balance); .then(() => setBalance(account, balance))
} .then(() => ethers.getSigner(account));
module.exports = { module.exports = {
impersonate, impersonate,

View File

@ -1,6 +1,7 @@
module.exports = { module.exports = {
// sum of integer / bignumber // sum of integer / bignumber
sum: (...args) => args.reduce((acc, n) => acc + n, 0), sum: (...args) => args.reduce((acc, n) => acc + n, 0),
bigintSum: (...args) => args.reduce((acc, n) => acc + n, 0n),
BNsum: (...args) => args.reduce((acc, n) => acc.add(n), web3.utils.toBN(0)), BNsum: (...args) => args.reduce((acc, n) => acc.add(n), web3.utils.toBN(0)),
// min of integer / bignumber // min of integer / bignumber
min: (...args) => args.slice(1).reduce((x, y) => (x < y ? x : y), args[0]), min: (...args) => args.slice(1).reduce((x, y) => (x < y ? x : y), args[0]),

View File

@ -1,134 +1,117 @@
const ethSigUtil = require('eth-sig-util'); const { ethers } = require('hardhat');
const Wallet = require('ethereumjs-wallet').default;
const { getDomain, domainType } = require('../helpers/eip712');
const { MAX_UINT48 } = require('../helpers/constants');
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai'); const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const ERC2771ContextMock = artifacts.require('ERC2771ContextMock'); const { impersonate } = require('../helpers/account');
const ERC2771Forwarder = artifacts.require('ERC2771Forwarder'); const { getDomain } = require('../helpers/eip712');
const ContextMockCaller = artifacts.require('ContextMockCaller'); const { MAX_UINT48 } = require('../helpers/constants');
const { shouldBehaveLikeRegularContext } = require('../utils/Context.behavior'); const { shouldBehaveLikeRegularContext } = require('../utils/Context.behavior');
contract('ERC2771Context', function (accounts) { async function fixture() {
const [, trustedForwarder] = accounts; const [sender] = await ethers.getSigners();
const forwarder = await ethers.deployContract('ERC2771Forwarder', []);
const forwarderAsSigner = await impersonate(forwarder.target);
const context = await ethers.deployContract('ERC2771ContextMock', [forwarder]);
const domain = await getDomain(forwarder);
const types = {
ForwardRequest: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'gas', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint48' },
{ name: 'data', type: 'bytes' },
],
};
return { sender, forwarder, forwarderAsSigner, context, domain, types };
}
describe('ERC2771Context', function () {
beforeEach(async function () { beforeEach(async function () {
this.forwarder = await ERC2771Forwarder.new('ERC2771Forwarder'); Object.assign(this, await loadFixture(fixture));
this.recipient = await ERC2771ContextMock.new(this.forwarder.address);
this.domain = await getDomain(this.forwarder);
this.types = {
EIP712Domain: domainType(this.domain),
ForwardRequest: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'gas', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint48' },
{ name: 'data', type: 'bytes' },
],
};
}); });
it('recognize trusted forwarder', async function () { it('recognize trusted forwarder', async function () {
expect(await this.recipient.isTrustedForwarder(this.forwarder.address)).to.equal(true); expect(await this.context.isTrustedForwarder(this.forwarder)).to.equal(true);
}); });
it('returns the trusted forwarder', async function () { it('returns the trusted forwarder', async function () {
expect(await this.recipient.trustedForwarder()).to.equal(this.forwarder.address); expect(await this.context.trustedForwarder()).to.equal(this.forwarder.target);
}); });
context('when called directly', function () { describe('when called directly', function () {
beforeEach(async function () { shouldBehaveLikeRegularContext();
this.context = this.recipient; // The Context behavior expects the contract in this.context
this.caller = await ContextMockCaller.new();
});
shouldBehaveLikeRegularContext(...accounts);
}); });
context('when receiving a relayed call', function () { describe('when receiving a relayed call', function () {
beforeEach(async function () {
this.wallet = Wallet.generate();
this.sender = web3.utils.toChecksumAddress(this.wallet.getAddressString());
this.data = {
types: this.types,
domain: this.domain,
primaryType: 'ForwardRequest',
};
});
describe('msgSender', function () { describe('msgSender', function () {
it('returns the relayed transaction original sender', async function () { it('returns the relayed transaction original sender', async function () {
const data = this.recipient.contract.methods.msgSender().encodeABI(); const nonce = await this.forwarder.nonces(this.sender);
const data = this.context.interface.encodeFunctionData('msgSender');
const req = { const req = {
from: this.sender, from: await this.sender.getAddress(),
to: this.recipient.address, to: await this.context.getAddress(),
value: '0', value: 0n,
gas: '100000',
nonce: (await this.forwarder.nonces(this.sender)).toString(),
deadline: MAX_UINT48,
data, data,
gas: 100000n,
nonce,
deadline: MAX_UINT48,
}; };
req.signature = ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { req.signature = await this.sender.signTypedData(this.domain, this.types, req);
data: { ...this.data, message: req },
});
expect(await this.forwarder.verify(req)).to.equal(true); expect(await this.forwarder.verify(req)).to.equal(true);
const { tx } = await this.forwarder.execute(req); await expect(this.forwarder.execute(req)).to.emit(this.context, 'Sender').withArgs(this.sender.address);
await expectEvent.inTransaction(tx, ERC2771ContextMock, 'Sender', { sender: this.sender });
}); });
it('returns the original sender when calldata length is less than 20 bytes (address length)', async function () { it('returns the original sender when calldata length is less than 20 bytes (address length)', async function () {
// The forwarder doesn't produce calls with calldata length less than 20 bytes // The forwarder doesn't produce calls with calldata length less than 20 bytes so `this.forwarderAsSigner` is used instead.
const recipient = await ERC2771ContextMock.new(trustedForwarder); await expect(this.context.connect(this.forwarderAsSigner).msgSender())
.to.emit(this.context, 'Sender')
const { receipt } = await recipient.msgSender({ from: trustedForwarder }); .withArgs(this.forwarder.target);
await expectEvent(receipt, 'Sender', { sender: trustedForwarder });
}); });
}); });
describe('msgData', function () { describe('msgData', function () {
it('returns the relayed transaction original data', async function () { it('returns the relayed transaction original data', async function () {
const integerValue = '42'; const args = [42n, 'OpenZeppelin'];
const stringValue = 'OpenZeppelin';
const data = this.recipient.contract.methods.msgData(integerValue, stringValue).encodeABI(); const nonce = await this.forwarder.nonces(this.sender);
const data = this.context.interface.encodeFunctionData('msgData', args);
const req = { const req = {
from: this.sender, from: await this.sender.getAddress(),
to: this.recipient.address, to: await this.context.getAddress(),
value: '0', value: 0n,
gas: '100000',
nonce: (await this.forwarder.nonces(this.sender)).toString(),
deadline: MAX_UINT48,
data, data,
gas: 100000n,
nonce,
deadline: MAX_UINT48,
}; };
req.signature = ethSigUtil.signTypedMessage(this.wallet.getPrivateKey(), { req.signature = this.sender.signTypedData(this.domain, this.types, req);
data: { ...this.data, message: req },
});
expect(await this.forwarder.verify(req)).to.equal(true); expect(await this.forwarder.verify(req)).to.equal(true);
const { tx } = await this.forwarder.execute(req); await expect(this.forwarder.execute(req))
await expectEvent.inTransaction(tx, ERC2771ContextMock, 'Data', { data, integerValue, stringValue }); .to.emit(this.context, 'Data')
.withArgs(data, ...args);
}); });
}); });
it('returns the full original data when calldata length is less than 20 bytes (address length)', async function () { it('returns the full original data when calldata length is less than 20 bytes (address length)', async function () {
// The forwarder doesn't produce calls with calldata length less than 20 bytes const data = this.context.interface.encodeFunctionData('msgDataShort');
const recipient = await ERC2771ContextMock.new(trustedForwarder);
const { receipt } = await recipient.msgDataShort({ from: trustedForwarder }); // The forwarder doesn't produce calls with calldata length less than 20 bytes so `this.forwarderAsSigner` is used instead.
await expect(await this.context.connect(this.forwarderAsSigner).msgDataShort())
const data = recipient.contract.methods.msgDataShort().encodeABI(); .to.emit(this.context, 'DataShort')
await expectEvent(receipt, 'DataShort', { data }); .withArgs(data);
}); });
}); });
}); });

View File

@ -1,245 +1,217 @@
const ethSigUtil = require('eth-sig-util'); const { ethers } = require('hardhat');
const Wallet = require('ethereumjs-wallet').default;
const { getDomain, domainType } = require('../helpers/eip712');
const { expectRevertCustomError } = require('../helpers/customError');
const { constants, expectRevert, expectEvent, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai'); const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const ERC2771Forwarder = artifacts.require('ERC2771Forwarder'); const { getDomain } = require('../helpers/eip712');
const CallReceiverMockTrustingForwarder = artifacts.require('CallReceiverMockTrustingForwarder'); const { bigint: time } = require('../helpers/time');
const { bigintSum: sum } = require('../helpers/math');
contract('ERC2771Forwarder', function (accounts) { async function fixture() {
const [, refundReceiver, another] = accounts; const [sender, refundReceiver, another, ...accounts] = await ethers.getSigners();
const tamperedValues = { const forwarder = await ethers.deployContract('ERC2771Forwarder', ['ERC2771Forwarder']);
from: another, const receiver = await ethers.deployContract('CallReceiverMockTrustingForwarder', [forwarder]);
value: web3.utils.toWei('0.5'), const domain = await getDomain(forwarder);
data: '0x1742', const types = {
ForwardRequest: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'gas', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint48' },
{ name: 'data', type: 'bytes' },
],
}; };
beforeEach(async function () { const forgeRequest = async (override = {}, signer = sender) => {
this.forwarder = await ERC2771Forwarder.new('ERC2771Forwarder'); const req = {
from: await signer.getAddress(),
this.domain = await getDomain(this.forwarder); to: await receiver.getAddress(),
this.types = { value: 0n,
EIP712Domain: domainType(this.domain), data: receiver.interface.encodeFunctionData('mockFunction'),
ForwardRequest: [ gas: 100000n,
{ name: 'from', type: 'address' }, deadline: (await time.clock.timestamp()) + 60n,
{ name: 'to', type: 'address' }, nonce: await forwarder.nonces(sender),
{ name: 'value', type: 'uint256' }, ...override,
{ name: 'gas', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint48' },
{ name: 'data', type: 'bytes' },
],
}; };
req.signature = await signer.signTypedData(domain, types, req);
return req;
};
this.alice = Wallet.generate(); const estimateRequest = request =>
this.alice.address = web3.utils.toChecksumAddress(this.alice.getAddressString()); ethers.provider.estimateGas({
from: forwarder,
this.timestamp = await time.latest(); to: request.to,
this.receiver = await CallReceiverMockTrustingForwarder.new(this.forwarder.address); data: ethers.solidityPacked(['bytes', 'address'], [request.data, request.from]),
this.request = { value: request.value,
from: this.alice.address, gasLimit: request.gas,
to: this.receiver.address,
value: '0',
gas: '100000',
data: this.receiver.contract.methods.mockFunction().encodeABI(),
deadline: this.timestamp.toNumber() + 60, // 1 minute
};
this.requestData = {
...this.request,
nonce: (await this.forwarder.nonces(this.alice.address)).toString(),
};
this.forgeData = request => ({
types: this.types,
domain: this.domain,
primaryType: 'ForwardRequest',
message: { ...this.requestData, ...request },
}); });
this.sign = (privateKey, request) =>
ethSigUtil.signTypedMessage(privateKey, {
data: this.forgeData(request),
});
this.estimateRequest = request =>
web3.eth.estimateGas({
from: this.forwarder.address,
to: request.to,
data: web3.utils.encodePacked({ value: request.data, type: 'bytes' }, { value: request.from, type: 'address' }),
value: request.value,
gas: request.gas,
});
this.requestData.signature = this.sign(this.alice.getPrivateKey()); return {
sender,
refundReceiver,
another,
accounts,
forwarder,
receiver,
forgeRequest,
estimateRequest,
domain,
types,
};
}
// values or function to tamper with a signed request.
const tamperedValues = {
from: ethers.Wallet.createRandom().address,
to: ethers.Wallet.createRandom().address,
value: ethers.parseEther('0.5'),
data: '0x1742',
signature: s => {
const t = ethers.toBeArray(s);
t[42] ^= 0xff;
return ethers.hexlify(t);
},
};
describe('ERC2771Forwarder', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
}); });
context('verify', function () { describe('verify', function () {
context('with valid signature', function () { describe('with valid signature', function () {
it('returns true without altering the nonce', async function () { it('returns true without altering the nonce', async function () {
expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal( const request = await this.forgeRequest();
web3.utils.toBN(this.requestData.nonce), expect(await this.forwarder.nonces(request.from)).to.be.equal(request.nonce);
); expect(await this.forwarder.verify(request)).to.be.equal(true);
expect(await this.forwarder.verify(this.requestData)).to.be.equal(true); expect(await this.forwarder.nonces(request.from)).to.be.equal(request.nonce);
expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
web3.utils.toBN(this.requestData.nonce),
);
}); });
}); });
context('with tampered values', function () { describe('with tampered values', function () {
for (const [key, value] of Object.entries(tamperedValues)) { for (const [key, value] of Object.entries(tamperedValues)) {
it(`returns false with tampered ${key}`, async function () { it(`returns false with tampered ${key}`, async function () {
expect(await this.forwarder.verify(this.forgeData({ [key]: value }).message)).to.be.equal(false); const request = await this.forgeRequest();
request[key] = typeof value == 'function' ? value(request[key]) : value;
expect(await this.forwarder.verify(request)).to.be.equal(false);
}); });
} }
it('returns false with an untrustful to', async function () {
expect(await this.forwarder.verify(this.forgeData({ to: another }).message)).to.be.equal(false);
});
it('returns false with tampered signature', async function () {
const tamperedsign = web3.utils.hexToBytes(this.requestData.signature);
tamperedsign[42] ^= 0xff;
this.requestData.signature = web3.utils.bytesToHex(tamperedsign);
expect(await this.forwarder.verify(this.requestData)).to.be.equal(false);
});
it('returns false with valid signature for non-current nonce', async function () { it('returns false with valid signature for non-current nonce', async function () {
const req = { const request = await this.forgeRequest({ nonce: 1337n });
...this.requestData, expect(await this.forwarder.verify(request)).to.be.equal(false);
nonce: this.requestData.nonce + 1,
};
req.signature = this.sign(this.alice.getPrivateKey(), req);
expect(await this.forwarder.verify(req)).to.be.equal(false);
}); });
it('returns false with valid signature for expired deadline', async function () { it('returns false with valid signature for expired deadline', async function () {
const req = { const request = await this.forgeRequest({ deadline: (await time.clock.timestamp()) - 1n });
...this.requestData, expect(await this.forwarder.verify(request)).to.be.equal(false);
deadline: this.timestamp - 1,
};
req.signature = this.sign(this.alice.getPrivateKey(), req);
expect(await this.forwarder.verify(req)).to.be.equal(false);
}); });
}); });
}); });
context('execute', function () { describe('execute', function () {
context('with valid requests', function () { describe('with valid requests', function () {
beforeEach(async function () {
expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal(
web3.utils.toBN(this.requestData.nonce),
);
});
it('emits an event and consumes nonce for a successful request', async function () { it('emits an event and consumes nonce for a successful request', async function () {
const receipt = await this.forwarder.execute(this.requestData); const request = await this.forgeRequest();
await expectEvent.inTransaction(receipt.tx, this.receiver, 'MockFunctionCalled');
await expectEvent.inTransaction(receipt.tx, this.forwarder, 'ExecutedForwardRequest', { expect(await this.forwarder.nonces(request.from)).to.equal(request.nonce);
signer: this.requestData.from,
nonce: web3.utils.toBN(this.requestData.nonce), await expect(this.forwarder.execute(request))
success: true, .to.emit(this.receiver, 'MockFunctionCalled')
}); .to.emit(this.forwarder, 'ExecutedForwardRequest')
expect(await this.forwarder.nonces(this.requestData.from)).to.be.bignumber.equal( .withArgs(request.from, request.nonce, true);
web3.utils.toBN(this.requestData.nonce + 1),
); expect(await this.forwarder.nonces(request.from)).to.be.equal(request.nonce + 1n);
}); });
it('reverts with an unsuccessful request', async function () { it('reverts with an unsuccessful request', async function () {
const req = { const request = await this.forgeRequest({
...this.requestData, data: this.receiver.interface.encodeFunctionData('mockFunctionRevertsNoReason'),
data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(), });
};
req.signature = this.sign(this.alice.getPrivateKey(), req); await expect(this.forwarder.execute(request)).to.be.revertedWithCustomError(this.forwarder, 'FailedInnerCall');
await expectRevertCustomError(this.forwarder.execute(req), 'FailedInnerCall', []);
}); });
}); });
context('with tampered request', function () { describe('with tampered request', function () {
for (const [key, value] of Object.entries(tamperedValues)) { for (const [key, value] of Object.entries(tamperedValues)) {
it(`reverts with tampered ${key}`, async function () { it(`reverts with tampered ${key}`, async function () {
const data = this.forgeData({ [key]: value }); const request = await this.forgeRequest();
await expectRevertCustomError( request[key] = typeof value == 'function' ? value(request[key]) : value;
this.forwarder.execute(data.message, {
value: key == 'value' ? value : 0, // To avoid MismatchedValue error const promise = this.forwarder.execute(request, { value: key == 'value' ? value : 0 });
}), if (key != 'to') {
'ERC2771ForwarderInvalidSigner', await expect(promise)
[ethSigUtil.recoverTypedSignature({ data, sig: this.requestData.signature }), data.message.from], .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderInvalidSigner')
); .withArgs(ethers.verifyTypedData(this.domain, this.types, request, request.signature), request.from);
} else {
await expect(promise)
.to.be.revertedWithCustomError(this.forwarder, 'ERC2771UntrustfulTarget')
.withArgs(request.to, this.forwarder.target);
}
}); });
} }
it('reverts with an untrustful to', async function () {
const data = this.forgeData({ to: another });
await expectRevertCustomError(this.forwarder.execute(data.message), 'ERC2771UntrustfulTarget', [
data.message.to,
this.forwarder.address,
]);
});
it('reverts with tampered signature', async function () {
const tamperedSig = web3.utils.hexToBytes(this.requestData.signature);
tamperedSig[42] ^= 0xff;
this.requestData.signature = web3.utils.bytesToHex(tamperedSig);
await expectRevertCustomError(this.forwarder.execute(this.requestData), 'ERC2771ForwarderInvalidSigner', [
ethSigUtil.recoverTypedSignature({ data: this.forgeData(), sig: tamperedSig }),
this.requestData.from,
]);
});
it('reverts with valid signature for non-current nonce', async function () { it('reverts with valid signature for non-current nonce', async function () {
// Execute first a request const request = await this.forgeRequest();
await this.forwarder.execute(this.requestData);
// And then fail due to an already used nonce // consume nonce
await expectRevertCustomError(this.forwarder.execute(this.requestData), 'ERC2771ForwarderInvalidSigner', [ await this.forwarder.execute(request);
ethSigUtil.recoverTypedSignature({
data: this.forgeData({ ...this.requestData, nonce: this.requestData.nonce + 1 }), // nonce has changed
sig: this.requestData.signature, await expect(this.forwarder.execute(request))
}), .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderInvalidSigner')
this.requestData.from, .withArgs(
]); ethers.verifyTypedData(
this.domain,
this.types,
{ ...request, nonce: request.nonce + 1n },
request.signature,
),
request.from,
);
}); });
it('reverts with valid signature for expired deadline', async function () { it('reverts with valid signature for expired deadline', async function () {
const req = { const request = await this.forgeRequest({ deadline: (await time.clock.timestamp()) - 1n });
...this.requestData,
deadline: this.timestamp - 1, await expect(this.forwarder.execute(request))
}; .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderExpiredRequest')
req.signature = this.sign(this.alice.getPrivateKey(), req); .withArgs(request.deadline);
await expectRevertCustomError(this.forwarder.execute(req), 'ERC2771ForwarderExpiredRequest', [
this.timestamp - 1,
]);
}); });
it('reverts with valid signature but mismatched value', async function () { it('reverts with valid signature but mismatched value', async function () {
const value = 100; const request = await this.forgeRequest({ value: 100n });
const req = {
...this.requestData, await expect(this.forwarder.execute(request))
value, .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderMismatchedValue')
}; .withArgs(request.value, 0n);
req.signature = this.sign(this.alice.getPrivateKey(), req);
await expectRevertCustomError(this.forwarder.execute(req), 'ERC2771ForwarderMismatchedValue', [0, value]);
}); });
}); });
it('bubbles out of gas', async function () { it('bubbles out of gas', async function () {
this.requestData.data = this.receiver.contract.methods.mockFunctionOutOfGas().encodeABI(); const request = await this.forgeRequest({
this.requestData.gas = 1_000_000; data: this.receiver.interface.encodeFunctionData('mockFunctionOutOfGas'),
this.requestData.signature = this.sign(this.alice.getPrivateKey()); gas: 1_000_000n,
});
const gasAvailable = 100_000; const gasLimit = 100_000n;
await expectRevert.assertion(this.forwarder.execute(this.requestData, { gas: gasAvailable })); await expect(this.forwarder.execute(request, { gasLimit })).to.be.revertedWithoutReason();
const { transactions } = await web3.eth.getBlock('latest'); const { gasUsed } = await ethers.provider
const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]); .getBlock('latest')
.then(block => block.getTransaction(0))
.then(tx => ethers.provider.getTransactionReceipt(tx.hash));
expect(gasUsed).to.be.equal(gasAvailable); expect(gasUsed).to.be.equal(gasLimit);
}); });
it('bubbles out of gas forced by the relayer', async function () { it('bubbles out of gas forced by the relayer', async function () {
const request = await this.forgeRequest();
// If there's an incentive behind executing requests, a malicious relayer could grief // If there's an incentive behind executing requests, a malicious relayer could grief
// the forwarder by executing requests and providing a top-level call gas limit that // the forwarder by executing requests and providing a top-level call gas limit that
// is too low to successfully finish the request after the 63/64 rule. // is too low to successfully finish the request after the 63/64 rule.
@ -247,294 +219,252 @@ contract('ERC2771Forwarder', function (accounts) {
// We set the baseline to the gas limit consumed by a successful request if it was executed // We set the baseline to the gas limit consumed by a successful request if it was executed
// normally. Note this includes the 21000 buffer that also the relayer will be charged to // normally. Note this includes the 21000 buffer that also the relayer will be charged to
// start a request execution. // start a request execution.
const estimate = await this.estimateRequest(this.request); const estimate = await this.estimateRequest(request);
// Because the relayer call consumes gas until the `CALL` opcode, the gas left after failing // Because the relayer call consumes gas until the `CALL` opcode, the gas left after failing
// the subcall won't enough to finish the top level call (after testing), so we add a // the subcall won't enough to finish the top level call (after testing), so we add a
// moderated buffer. // moderated buffer.
const gasAvailable = estimate + 2_000; const gasLimit = estimate + 2_000n;
// The subcall out of gas should be caught by the contract and then bubbled up consuming // The subcall out of gas should be caught by the contract and then bubbled up consuming
// the available gas with an `invalid` opcode. // the available gas with an `invalid` opcode.
await expectRevert.outOfGas(this.forwarder.execute(this.requestData, { gas: gasAvailable })); await expect(this.forwarder.execute(request, { gasLimit })).to.be.revertedWithoutReason();
const { transactions } = await web3.eth.getBlock('latest'); const { gasUsed } = await ethers.provider
const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]); .getBlock('latest')
.then(block => block.getTransaction(0))
.then(tx => ethers.provider.getTransactionReceipt(tx.hash));
// We assert that indeed the gas was totally consumed. // We assert that indeed the gas was totally consumed.
expect(gasUsed).to.be.equal(gasAvailable); expect(gasUsed).to.be.equal(gasLimit);
}); });
}); });
context('executeBatch', function () { describe('executeBatch', function () {
const batchValue = requestDatas => requestDatas.reduce((value, request) => value + Number(request.value), 0); const requestsValue = requests => sum(...requests.map(request => request.value));
const requestCount = 3;
const idx = 1; // index that will be tampered with
beforeEach(async function () { beforeEach(async function () {
this.bob = Wallet.generate(); this.forgeRequests = override =>
this.bob.address = web3.utils.toChecksumAddress(this.bob.getAddressString()); Promise.all(this.accounts.slice(0, requestCount).map(signer => this.forgeRequest(override, signer)));
this.requests = await this.forgeRequests({ value: 10n });
this.eve = Wallet.generate(); this.value = requestsValue(this.requests);
this.eve.address = web3.utils.toChecksumAddress(this.eve.getAddressString());
this.signers = [this.alice, this.bob, this.eve];
this.requestDatas = await Promise.all(
this.signers.map(async ({ address }) => ({
...this.requestData,
from: address,
nonce: (await this.forwarder.nonces(address)).toString(),
value: web3.utils.toWei('10', 'gwei'),
})),
);
this.requestDatas = this.requestDatas.map((requestData, i) => ({
...requestData,
signature: this.sign(this.signers[i].getPrivateKey(), requestData),
}));
this.msgValue = batchValue(this.requestDatas);
this.gasUntil = async reqIdx => {
const gas = 0;
const estimations = await Promise.all(
new Array(reqIdx + 1).fill().map((_, idx) => this.estimateRequest(this.requestDatas[idx])),
);
return estimations.reduce((acc, estimation) => acc + estimation, gas);
};
}); });
context('with valid requests', function () { describe('with valid requests', function () {
beforeEach(async function () { it('sanity', async function () {
for (const request of this.requestDatas) { for (const request of this.requests) {
expect(await this.forwarder.verify(request)).to.be.equal(true); expect(await this.forwarder.verify(request)).to.be.equal(true);
} }
this.receipt = await this.forwarder.executeBatch(this.requestDatas, another, { value: this.msgValue });
}); });
it('emits events', async function () { it('emits events', async function () {
for (const request of this.requestDatas) { const receipt = this.forwarder.executeBatch(this.requests, this.another, { value: this.value });
await expectEvent.inTransaction(this.receipt.tx, this.receiver, 'MockFunctionCalled');
await expectEvent.inTransaction(this.receipt.tx, this.forwarder, 'ExecutedForwardRequest', { for (const request of this.requests) {
signer: request.from, await expect(receipt)
nonce: web3.utils.toBN(request.nonce), .to.emit(this.receiver, 'MockFunctionCalled')
success: true, .to.emit(this.forwarder, 'ExecutedForwardRequest')
}); .withArgs(request.from, request.nonce, true);
} }
}); });
it('increase nonces', async function () { it('increase nonces', async function () {
for (const request of this.requestDatas) { await this.forwarder.executeBatch(this.requests, this.another, { value: this.value });
expect(await this.forwarder.nonces(request.from)).to.be.bignumber.eq(web3.utils.toBN(request.nonce + 1));
for (const request of this.requests) {
expect(await this.forwarder.nonces(request.from)).to.be.equal(request.nonce + 1n);
} }
}); });
}); });
context('with tampered requests', function () { describe('with tampered requests', function () {
beforeEach(async function () {
this.idx = 1; // Tampered idx
});
it('reverts with mismatched value', async function () { it('reverts with mismatched value', async function () {
this.requestDatas[this.idx].value = 100; // tamper value of one of the request + resign
this.requestDatas[this.idx].signature = this.sign( this.requests[idx] = await this.forgeRequest({ value: 100n }, this.accounts[1]);
this.signers[this.idx].getPrivateKey(),
this.requestDatas[this.idx], await expect(this.forwarder.executeBatch(this.requests, this.another, { value: this.value }))
); .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderMismatchedValue')
await expectRevertCustomError( .withArgs(requestsValue(this.requests), this.value);
this.forwarder.executeBatch(this.requestDatas, another, { value: this.msgValue }),
'ERC2771ForwarderMismatchedValue',
[batchValue(this.requestDatas), this.msgValue],
);
}); });
context('when the refund receiver is the zero address', function () { describe('when the refund receiver is the zero address', function () {
beforeEach(function () { beforeEach(function () {
this.refundReceiver = constants.ZERO_ADDRESS; this.refundReceiver = ethers.ZeroAddress;
}); });
for (const [key, value] of Object.entries(tamperedValues)) { for (const [key, value] of Object.entries(tamperedValues)) {
it(`reverts with at least one tampered request ${key}`, async function () { it(`reverts with at least one tampered request ${key}`, async function () {
const data = this.forgeData({ ...this.requestDatas[this.idx], [key]: value }); this.requests[idx][key] = typeof value == 'function' ? value(this.requests[idx][key]) : value;
this.requestDatas[this.idx] = data.message; const promise = this.forwarder.executeBatch(this.requests, this.refundReceiver, { value: this.value });
if (key != 'to') {
await expectRevertCustomError( await expect(promise)
this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }), .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderInvalidSigner')
'ERC2771ForwarderInvalidSigner', .withArgs(
[ ethers.verifyTypedData(this.domain, this.types, this.requests[idx], this.requests[idx].signature),
ethSigUtil.recoverTypedSignature({ data, sig: this.requestDatas[this.idx].signature }), this.requests[idx].from,
data.message.from, );
], } else {
); await expect(promise)
.to.be.revertedWithCustomError(this.forwarder, 'ERC2771UntrustfulTarget')
.withArgs(this.requests[idx].to, this.forwarder.target);
}
}); });
} }
it('reverts with at least one untrustful to', async function () {
const data = this.forgeData({ ...this.requestDatas[this.idx], to: another });
this.requestDatas[this.idx] = data.message;
await expectRevertCustomError(
this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
'ERC2771UntrustfulTarget',
[this.requestDatas[this.idx].to, this.forwarder.address],
);
});
it('reverts with at least one tampered request signature', async function () {
const tamperedSig = web3.utils.hexToBytes(this.requestDatas[this.idx].signature);
tamperedSig[42] ^= 0xff;
this.requestDatas[this.idx].signature = web3.utils.bytesToHex(tamperedSig);
await expectRevertCustomError(
this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
'ERC2771ForwarderInvalidSigner',
[
ethSigUtil.recoverTypedSignature({
data: this.forgeData(this.requestDatas[this.idx]),
sig: this.requestDatas[this.idx].signature,
}),
this.requestDatas[this.idx].from,
],
);
});
it('reverts with at least one valid signature for non-current nonce', async function () { it('reverts with at least one valid signature for non-current nonce', async function () {
// Execute first a request // Execute first a request
await this.forwarder.execute(this.requestDatas[this.idx], { value: this.requestDatas[this.idx].value }); await this.forwarder.execute(this.requests[idx], { value: this.requests[idx].value });
// And then fail due to an already used nonce // And then fail due to an already used nonce
await expectRevertCustomError( await expect(this.forwarder.executeBatch(this.requests, this.refundReceiver, { value: this.value }))
this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }), .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderInvalidSigner')
'ERC2771ForwarderInvalidSigner', .withArgs(
[ ethers.verifyTypedData(
ethSigUtil.recoverTypedSignature({ this.domain,
data: this.forgeData({ ...this.requestDatas[this.idx], nonce: this.requestDatas[this.idx].nonce + 1 }), this.types,
sig: this.requestDatas[this.idx].signature, { ...this.requests[idx], nonce: this.requests[idx].nonce + 1n },
}), this.requests[idx].signature,
this.requestDatas[this.idx].from, ),
], this.requests[idx].from,
); );
}); });
it('reverts with at least one valid signature for expired deadline', async function () { it('reverts with at least one valid signature for expired deadline', async function () {
this.requestDatas[this.idx].deadline = this.timestamp.toNumber() - 1; this.requests[idx] = await this.forgeRequest(
this.requestDatas[this.idx].signature = this.sign( { ...this.requests[idx], deadline: (await time.clock.timestamp()) - 1n },
this.signers[this.idx].getPrivateKey(), this.accounts[1],
this.requestDatas[this.idx],
);
await expectRevertCustomError(
this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { value: this.msgValue }),
'ERC2771ForwarderExpiredRequest',
[this.timestamp.toNumber() - 1],
); );
await expect(this.forwarder.executeBatch(this.requests, this.refundReceiver, { value: this.amount }))
.to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderExpiredRequest')
.withArgs(this.requests[idx].deadline);
}); });
}); });
context('when the refund receiver is a known address', function () { describe('when the refund receiver is a known address', function () {
beforeEach(async function () { beforeEach(async function () {
this.refundReceiver = refundReceiver; this.initialRefundReceiverBalance = await ethers.provider.getBalance(this.refundReceiver);
this.initialRefundReceiverBalance = web3.utils.toBN(await web3.eth.getBalance(this.refundReceiver)); this.initialTamperedRequestNonce = await this.forwarder.nonces(this.requests[idx].from);
this.initialTamperedRequestNonce = await this.forwarder.nonces(this.requestDatas[this.idx].from);
}); });
for (const [key, value] of Object.entries(tamperedValues)) { for (const [key, value] of Object.entries(tamperedValues)) {
it(`ignores a request with tampered ${key} and refunds its value`, async function () { it(`ignores a request with tampered ${key} and refunds its value`, async function () {
const data = this.forgeData({ ...this.requestDatas[this.idx], [key]: value }); this.requests[idx][key] = typeof value == 'function' ? value(this.requests[idx][key]) : value;
this.requestDatas[this.idx] = data.message; const events = await this.forwarder
.executeBatch(this.requests, this.refundReceiver, { value: requestsValue(this.requests) })
.then(tx => tx.wait())
.then(receipt =>
receipt.logs.filter(
log => log?.fragment?.type == 'event' && log?.fragment?.name == 'ExecutedForwardRequest',
),
);
const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { expect(events).to.have.lengthOf(this.requests.length - 1);
value: batchValue(this.requestDatas),
});
expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2);
}); });
} }
it('ignores a request with a valid signature for non-current nonce', async function () { it('ignores a request with a valid signature for non-current nonce', async function () {
// Execute first a request // Execute first a request
await this.forwarder.execute(this.requestDatas[this.idx], { value: this.requestDatas[this.idx].value }); await this.forwarder.execute(this.requests[idx], { value: this.requests[idx].value });
this.initialTamperedRequestNonce++; // Should be already incremented by the individual `execute` this.initialTamperedRequestNonce++; // Should be already incremented by the individual `execute`
// And then ignore the same request in a batch due to an already used nonce // And then ignore the same request in a batch due to an already used nonce
const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { const events = await this.forwarder
value: this.msgValue, .executeBatch(this.requests, this.refundReceiver, { value: this.value })
}); .then(tx => tx.wait())
expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2); .then(receipt =>
receipt.logs.filter(
log => log?.fragment?.type == 'event' && log?.fragment?.name == 'ExecutedForwardRequest',
),
);
expect(events).to.have.lengthOf(this.requests.length - 1);
}); });
it('ignores a request with a valid signature for expired deadline', async function () { it('ignores a request with a valid signature for expired deadline', async function () {
this.requestDatas[this.idx].deadline = this.timestamp.toNumber() - 1; this.requests[idx] = await this.forgeRequest(
this.requestDatas[this.idx].signature = this.sign( { ...this.requests[idx], deadline: (await time.clock.timestamp()) - 1n },
this.signers[this.idx].getPrivateKey(), this.accounts[1],
this.requestDatas[this.idx],
); );
const receipt = await this.forwarder.executeBatch(this.requestDatas, this.refundReceiver, { const events = await this.forwarder
value: this.msgValue, .executeBatch(this.requests, this.refundReceiver, { value: this.value })
}); .then(tx => tx.wait())
expect(receipt.logs.filter(({ event }) => event === 'ExecutedForwardRequest').length).to.be.equal(2); .then(receipt =>
receipt.logs.filter(
log => log?.fragment?.type == 'event' && log?.fragment?.name == 'ExecutedForwardRequest',
),
);
expect(events).to.have.lengthOf(this.requests.length - 1);
}); });
afterEach(async function () { afterEach(async function () {
// The invalid request value was refunded // The invalid request value was refunded
expect(await web3.eth.getBalance(this.refundReceiver)).to.be.bignumber.equal( expect(await ethers.provider.getBalance(this.refundReceiver)).to.be.equal(
this.initialRefundReceiverBalance.add(web3.utils.toBN(this.requestDatas[this.idx].value)), this.initialRefundReceiverBalance + this.requests[idx].value,
); );
// The invalid request from's nonce was not incremented // The invalid request from's nonce was not incremented
expect(await this.forwarder.nonces(this.requestDatas[this.idx].from)).to.be.bignumber.eq( expect(await this.forwarder.nonces(this.requests[idx].from)).to.be.equal(this.initialTamperedRequestNonce);
web3.utils.toBN(this.initialTamperedRequestNonce),
);
}); });
}); });
it('bubbles out of gas', async function () { it('bubbles out of gas', async function () {
this.requestDatas[this.idx].data = this.receiver.contract.methods.mockFunctionOutOfGas().encodeABI(); this.requests[idx] = await this.forgeRequest({
this.requestDatas[this.idx].gas = 1_000_000; data: this.receiver.interface.encodeFunctionData('mockFunctionOutOfGas'),
this.requestDatas[this.idx].signature = this.sign( gas: 1_000_000n,
this.signers[this.idx].getPrivateKey(), });
this.requestDatas[this.idx],
);
const gasAvailable = 300_000; const gasLimit = 300_000n;
await expectRevert.assertion( await expect(
this.forwarder.executeBatch(this.requestDatas, constants.ZERO_ADDRESS, { this.forwarder.executeBatch(this.requests, ethers.ZeroAddress, {
gas: gasAvailable, gasLimit,
value: this.requestDatas.reduce((acc, { value }) => acc + Number(value), 0), value: requestsValue(this.requests),
}), }),
); ).to.be.revertedWithoutReason();
const { transactions } = await web3.eth.getBlock('latest'); const { gasUsed } = await ethers.provider
const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]); .getBlock('latest')
.then(block => block.getTransaction(0))
.then(tx => ethers.provider.getTransactionReceipt(tx.hash));
expect(gasUsed).to.be.equal(gasAvailable); expect(gasUsed).to.be.equal(gasLimit);
}); });
it('bubbles out of gas forced by the relayer', async function () { it('bubbles out of gas forced by the relayer', async function () {
// Similarly to the single execute, a malicious relayer could grief requests. // Similarly to the single execute, a malicious relayer could grief requests.
// We estimate until the selected request as if they were executed normally // We estimate until the selected request as if they were executed normally
const estimate = await this.gasUntil(this.requestDatas, this.idx); const estimate = await Promise.all(this.requests.slice(0, idx + 1).map(this.estimateRequest)).then(gas =>
sum(...gas),
);
// We add a Buffer to account for all the gas that's used before the selected call. // We add a Buffer to account for all the gas that's used before the selected call.
// Note is slightly bigger because the selected request is not the index 0 and it affects // Note is slightly bigger because the selected request is not the index 0 and it affects
// the buffer needed. // the buffer needed.
const gasAvailable = estimate + 10_000; const gasLimit = estimate + 10_000n;
// The subcall out of gas should be caught by the contract and then bubbled up consuming // The subcall out of gas should be caught by the contract and then bubbled up consuming
// the available gas with an `invalid` opcode. // the available gas with an `invalid` opcode.
await expectRevert.outOfGas( await expect(
this.forwarder.executeBatch(this.requestDatas, constants.ZERO_ADDRESS, { gas: gasAvailable }), this.forwarder.executeBatch(this.requests, ethers.ZeroAddress, {
); gasLimit,
value: requestsValue(this.requests),
}),
).to.be.revertedWithoutReason();
const { transactions } = await web3.eth.getBlock('latest'); const { gasUsed } = await ethers.provider
const { gasUsed } = await web3.eth.getTransactionReceipt(transactions[0]); .getBlock('latest')
.then(block => block.getTransaction(0))
.then(tx => ethers.provider.getTransactionReceipt(tx.hash));
// We assert that indeed the gas was totally consumed. // We assert that indeed the gas was totally consumed.
expect(gasUsed).to.be.equal(gasAvailable); expect(gasUsed).to.be.equal(gasLimit);
}); });
}); });
}); });

View File

@ -1,38 +1,46 @@
const { BN, expectEvent } = require('@openzeppelin/test-helpers'); const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const ContextMock = artifacts.require('ContextMock'); async function fixture() {
return { contextHelper: await ethers.deployContract('ContextMockCaller', []) };
}
function shouldBehaveLikeRegularContext() {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
function shouldBehaveLikeRegularContext(sender) {
describe('msgSender', function () { describe('msgSender', function () {
it('returns the transaction sender when called from an EOA', async function () { it('returns the transaction sender when called from an EOA', async function () {
const receipt = await this.context.msgSender({ from: sender }); await expect(this.context.connect(this.sender).msgSender())
expectEvent(receipt, 'Sender', { sender }); .to.emit(this.context, 'Sender')
.withArgs(this.sender.address);
}); });
it('returns the transaction sender when from another contract', async function () { it('returns the transaction sender when called from another contract', async function () {
const { tx } = await this.caller.callSender(this.context.address, { from: sender }); await expect(this.contextHelper.connect(this.sender).callSender(this.context))
await expectEvent.inTransaction(tx, ContextMock, 'Sender', { sender: this.caller.address }); .to.emit(this.context, 'Sender')
.withArgs(this.contextHelper.target);
}); });
}); });
describe('msgData', function () { describe('msgData', function () {
const integerValue = new BN('42'); const args = [42n, 'OpenZeppelin'];
const stringValue = 'OpenZeppelin';
let callData;
beforeEach(async function () {
callData = this.context.contract.methods.msgData(integerValue.toString(), stringValue).encodeABI();
});
it('returns the transaction data when called from an EOA', async function () { it('returns the transaction data when called from an EOA', async function () {
const receipt = await this.context.msgData(integerValue, stringValue); const callData = this.context.interface.encodeFunctionData('msgData', args);
expectEvent(receipt, 'Data', { data: callData, integerValue, stringValue });
await expect(this.context.msgData(...args))
.to.emit(this.context, 'Data')
.withArgs(callData, ...args);
}); });
it('returns the transaction sender when from another contract', async function () { it('returns the transaction sender when from another contract', async function () {
const { tx } = await this.caller.callData(this.context.address, integerValue, stringValue); const callData = this.context.interface.encodeFunctionData('msgData', args);
await expectEvent.inTransaction(tx, ContextMock, 'Data', { data: callData, integerValue, stringValue });
await expect(this.contextHelper.callData(this.context, ...args))
.to.emit(this.context, 'Data')
.withArgs(callData, ...args);
}); });
}); });
} }

View File

@ -1,17 +1,18 @@
require('@openzeppelin/test-helpers'); const { ethers } = require('hardhat');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const ContextMock = artifacts.require('ContextMock');
const ContextMockCaller = artifacts.require('ContextMockCaller');
const { shouldBehaveLikeRegularContext } = require('./Context.behavior'); const { shouldBehaveLikeRegularContext } = require('./Context.behavior');
contract('Context', function (accounts) { async function fixture() {
const [sender] = accounts; const [sender] = await ethers.getSigners();
const context = await ethers.deployContract('ContextMock', []);
return { sender, context };
}
describe('Context', function () {
beforeEach(async function () { beforeEach(async function () {
this.context = await ContextMock.new(); Object.assign(this, await loadFixture(fixture));
this.caller = await ContextMockCaller.new();
}); });
shouldBehaveLikeRegularContext(sender); shouldBehaveLikeRegularContext();
}); });