Solidity
帶有返回非字元串值的字元串的 expectEvent
我使用
expectEvent
的是 OpenZeppelin 的Test Helpers,當執行 Truffle 測試來檢查事件時,地址和整數欄位都可以,但 字元串類型有問題。給定具有此事件和功能的智能合約:
event WithdrawERC20Token( string indexed tokenSymbol, address to, uint256 amount ); function withdrawERC20( string calldata tokenSymbol, address to, uint256 amount ) external { //... emit WithdrawERC20Token(tokenSymbol, to, amount); }
而這個測試:
const { expectEvent } = require('@openzeppelin/test-helpers'); // ... it('should withdraw ERC20 tokens', async () => { // const txReceipt = await swapManagerContract.withdrawERC20Token( 'UNI', investor1, 50 ); expectEvent(txReceipt, 'WithdrawERC20Token', { tokenSymbol: 'UNI', to: investor1, amount: new BN(50), }); }
我收到此輸出錯誤:
expected event argument 'tokenSymbol' to have value UNI but got 0xfba01d52a7cd84480d0573725899486a0b5e55c20ff45d6628874349375d1650 + expected - actual -0xfba01d52a7cd84480d0573725899486a0b5e55c20ff45d6628874349375d1650 +UNI
看起來它
tokenSymbol
以一種六進制格式儲存在 EVM 中。我嘗試對字元串 ‘UNI’ (fromAscii、asciiToHex等)應用多種轉換,但沒有將此字元串轉換為 ‘0xfba01d52a7cd84480d0573725899486a0b5e55c20ff45d6628874349375d1650’。關於如何使用
expectEvent
函式從事件中檢查字元串的任何線索?
正如評論中所指出的,該字元串是一個無界索引欄位,因此使用
keccak256
. 這可以反過來用於比較測試中的值。換句話說,這個改變對我有用:
expectEvent(txReceipt, 'WithdrawERC20Token', { tokenSymbol: web3.utils.keccak256('UNI'), to: investor1, amount: new BN(50), });