@ethereum-waffle/chai
Version:
A sweet set of chai matchers for your blockchain testing needs.
50 lines • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.supportChangeTokenBalance = void 0;
const ethers_1 = require("ethers");
const call_promise_1 = require("../call-promise");
const account_1 = require("./misc/account");
function supportChangeTokenBalance(Assertion) {
Assertion.addMethod('changeTokenBalance', function (token, account, balanceChange, errorMargin) {
(0, call_promise_1.callPromise)(this);
const isNegated = this.__flags.negate === true;
const derivedPromise = this.callPromise.then(async () => {
if (!('txReceipt' in this)) {
throw new Error('The changeTokenBalance matcher must be called on a transaction');
}
const address = typeof account === 'string' ? account : await (0, account_1.getAddressOf)(account);
const actualChanges = await getBalanceChange(this.txReceipt, token, address);
return [actualChanges, address];
}).then(([actualChange, address]) => {
const isCurrentlyNegated = this.__flags.negate === true;
this.__flags.negate = isNegated;
if (errorMargin === undefined)
errorMargin = '0';
if (ethers_1.BigNumber.from(errorMargin).eq(0)) {
this.assert(actualChange.lte(ethers_1.BigNumber.from(balanceChange).add(errorMargin)) &&
actualChange.gte(ethers_1.BigNumber.from(balanceChange).sub(errorMargin)), `Expected "${address}" to change balance by ${balanceChange} wei, ` +
`but it has changed by ${actualChange} wei`, `Expected "${address}" to not change balance by ${balanceChange} wei,`, balanceChange, actualChange);
}
else {
const low = ethers_1.BigNumber.from(balanceChange).sub(errorMargin);
const high = ethers_1.BigNumber.from(balanceChange).add(errorMargin);
this.assert(actualChange.lte(high) &&
actualChange.gte(low), `Expected "${address}" balance to change within [${[low, high]}] wei, ` +
`but it has changed by ${actualChange} wei`, `Expected "${address}" balance to not change within [${[low, high]}] wei`, balanceChange, actualChange);
}
this.__flags.negate = isCurrentlyNegated;
});
this.then = derivedPromise.then.bind(derivedPromise);
this.catch = derivedPromise.catch.bind(derivedPromise);
this.callPromise = derivedPromise;
return this;
});
}
exports.supportChangeTokenBalance = supportChangeTokenBalance;
async function getBalanceChange(txReceipt, token, address) {
const txBlockNumber = txReceipt.blockNumber;
const balanceBefore = await token['balanceOf(address)'](address, { blockTag: txBlockNumber - 1 });
const balanceAfter = await token['balanceOf(address)'](address, { blockTag: txBlockNumber });
return balanceAfter.sub(balanceBefore);
}
//# sourceMappingURL=changeTokenBalance.js.map