Truffle
Truffle 腳本:從賬戶轉移乙太幣後,不顯示智能合約 (SC) 的目前餘額222立即地
我有一個智能合約(SC1):
pragma solidity ^0.5.8; contract MySC1 { address owner; constructor() public { owner = msg.sender; } function sendTo(address payable receiver, uint amount) public { receiver.transfer(amount); } function() external payable{ } }
我正在從 account2 轉移它的乙太幣,但是當我檢查餘額時它仍然為零:
$ truffle exec ts4.js Using network 'development'. acc2 balance 100000000000000000000 address 0xEa719Cf8f777350c0D0B0be8cc4A90Aa95f36898 SC1 deployed 0x43ba105f5DeC27B9c4183c95971672e53EaA9a64 SC2 deployed 0xc80c3fDE077Ce7360e738BB6525A92bf7953ea51 Initial SC1: 0x43ba105f5DeC27B9c4183c95971672e53EaA9a64 balance is 0 Initial SC2: 0xc80c3fDE077Ce7360e738BB6525A92bf7953ea51 balance is 0 11 Ether from 0xEa719Cf8f777350c0D0B0be8cc4A90Aa95f36898, sc1: 0x43ba105f5DeC27B9c4183c95971672e53EaA9a64 balance is 0
但是當我再次執行腳本時,它顯示了正確的平衡:
$ truffle exec ts4.js Using network 'development'. acc2 balance 88999579200000000000 address 0xEa719Cf8f777350c0D0B0be8cc4A90Aa95f36898 SC1 deployed 0x43ba105f5DeC27B9c4183c95971672e53EaA9a64 SC2 deployed 0xc80c3fDE077Ce7360e738BB6525A92bf7953ea51 Initial SC1: 0x43ba105f5DeC27B9c4183c95971672e53EaA9a64 balance is 11000000000000000000 Initial SC2: 0xc80c3fDE077Ce7360e738BB6525A92bf7953ea51 balance is 0 11 Ether from 0xEa719Cf8f777350c0D0B0be8cc4A90Aa95f36898, sc1: 0x43ba105f5DeC27B9c4183c95971672e53EaA9a64 balance is 11000000000000000000
我的腳本是:
// Contracts const MySC1 = artifacts.require("MySC1") module.exports = async function(callback) { try { // Fetch accounts from wallet - these are unlocked const accounts = await web3.eth.getAccounts() // Set up account to transferEther to Victim const acc2 = accounts[2] acc2bal = await web3.eth.getBalance(acc2) web3.utils.fromWei(acc2bal, "ether") console.log('acc2 balance', acc2bal, 'address',acc2) // Fetch the deployed exchange const sc1 = await MySC1.deployed() console.log('SC1 deployed', sc1.address) sc1bal = await web3.eth.getBalance(sc1.address) web3.utils.fromWei(sc1bal, "ether") console.log(`Initial SC1:`,sc1.address,` balance is ${sc1bal}`) amount = '11' web3.eth.sendTransaction({to:sc1.address, from:acc2, value: web3.utils.toWei(amount)}) sc1bal = await web3.eth.getBalance(sc1.address) web3.utils.fromWei(sc1bal, "ether") console.log(`${amount} Ether from ${acc2}, sc1:`, sc1.address,` balance is ${sc1bal}`) } catch(error) { console.log(error) } callback() }
您可以嘗試等待 sendTransaction 嗎?
await web3.eth.sendTransaction({to:sc1.address, from:acc2, value: web3.utils.toWei(amount)})