我正在尝试将wei / eth发送到具有外部应付款回退功能的团结合同的地址。我下面的松露javascript测试不会导致instance.address的余额变差。 instance.address不是智能合约地址接收方吗?谁能发现console.logging余额为何为0的原因?还是发现我所缺少的东西?
谢谢!
const TestContract = artifacts.require("TestContract");
contract('TestContract', async (accounts) => {
it('should send 1 ether to TestContract', async () => {
let instance = await TestContract.deployed();
instance.send({from: accounts[1], value: 1000000000000000000});
let balance = await web3.eth.getBalance(instance.address);
console.log('instance.address balance: ' + parseInt(balance));
)}
答案 0 :(得分:1)
由于您没有在问题中提供合同,因此我在此假设您的合同如下所示。
文件路径:
./ contracts / TestContract.sol
pragma solidity ^0.4.23;
contract TestContract {
// all logic goes here...
function() public payable {
// payable fallback to receive and store ETH
}
}
因此,如果您想使用JS从accounts[1]
到TestContract
发送ETH,请按以下步骤操作:
文件路径:
./ test / TestContract.js
const tc = artifacts.require("TestContract");
contract('TestContract', async (accounts) => {
let instance;
// Runs before all tests in this block.
// Read about .new() VS .deployed() here:
// https://twitter.com/zulhhandyplast/status/1026181801239171072
before(async () => {
instance = await tc.new();
})
it('TestContract balance should starts with 0 ETH', async () => {
let balance = await web3.eth.getBalance(instance.address);
assert.equal(balance, 0);
})
it('TestContract balance should has 1 ETH after deposit', async () => {
let one_eth = web3.toWei(1, "ether");
await web3.eth.sendTransaction({from: accounts[1], to: instance.address, value: one_eth});
let balance_wei = await web3.eth.getBalance(instance.address);
let balance_ether = web3.fromWei(balance_wei.toNumber(), "ether");
assert.equal(balance_ether, 1);
})
})
请参阅上面代码中的注释,以了解有关Truffle中.new()
和.deployed()
关键字之间差异的更多信息。
我的解决方案的完整源代码可以在here中找到。
答案 1 :(得分:0)
您最不希望发送到一个地址,而不是一个对象。
instance.address.send({from: accounts[1], value: 1000000000000000000});
答案 2 :(得分:0)
解决了!我忘了我必须通过web3和eth发送交易,如下所示:
web3.eth.sendTransaction({})
还是谢谢!
答案 3 :(得分:0)
用于在您的松露测试文件中使用 Web3.js v1.4.0
。
const SolidityTest = artifacts.require('SolidityTest');
contract('SolidityTest', (accounts) => {
let solidityTest;
before(async () => {
solidityTest = await SolidityTest.new();
})
it('Test something', async () => {
// Send 100 wei to the contract.
// `sendEth` is your payable method.
await solidityTest.sendEth({from: accounts[1], value: 100});
// Check account 1 balance.
let acc1Balance = await web3.eth.getBalance(accounts[1]);
// Convert the unit from wei to eth
acc1Balance = web3.utils.fromWei(acc1Balance, 'ether')
console.log('acc1 balance:', acc1Balance)
// Check the contract balance.
let contractBalance = await web3.eth.getBalance(solidityTest.address);
contractBalance = web3.utils.fromWei(contractBalance, 'ether')
console.log('contract balance:', contractBalance)
});
});