Важный:
Я тестирую простой контракт, который получает эфир с одной учетной записи, разделяет значение и передает его на 3 другие учетные записи.
contract testContract {
address[] employees = [
0x4cd28d9a0d66216382ad3e1c993797989d1a8e05,
0xb871e16d7192cbaa2b5be32f85c1a19f61b8a50d,
0x5e5527378c42b91e95fee2cfbe974259d983a99e
];
function testContract() payable {
}
function () payable {
uint amountPerEmployee = msg.value / employees.length;
for(uint i = 0; i <= employees.length; i++) {
employees[i].transfer(amountPerEmployee);
}
}
}
При запуске функции обратного вызова с циклом я получаю сообщение об ошибке:
обратный вызов не содержит результата Ошибка: Ошибка: Исключение виртуальной машины при выполнении eth_estimateGas: неверный код операции в /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:59368:17 в /usr/local/lib/node_modules /ethereumjs-testrpc/build/cli.node.js:69306:5 в /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:11335:9 в /usr/local/lib/node_modules /ethereumjs-testrpc/build/cli.node.js:7895:16 при пополнении (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:8415:25) при iterateeCallback (/usr/ local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:8405:17) в /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:8380:16 в /usr /local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:11332:13 в /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:69302:9 в /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:63982:7
При тестировании функции обратного вызова, как показано ниже, все идет хорошо:
function () payable {
uint amountPerEmployee = msg.value / employees.length;
// Test with only the first item in the array, no loop
employees[0].transfer(amountPerEmployee);
}
Что здесь происходит? Это петля, которая использует слишком много газа?
Вы уходите с конца массива с
for(uint i = 0; i <= employees.length; i++)
employees[]
имеет ровно 3 строки, а именно: 0, 1, 2
.
Вы позволяете i
быть 3
тому, чего нет, поэтому оно не счастливо.
Соответствующий совет на потом, когда вы пойдете вперед. Вы захотите полностью изменить цикл из картины по соображениям масштабируемости.
Надеюсь, поможет.
Робберт