Last updated on 8 months ago
转账给普通账户
我们可以通过web3.js的接口进行转账
通过web3.js进行转账
1
| web3.eth.sendTransaction({from: accounts[0], to: accounst[1],value: 10});
|
在truffle中使用test脚本转账
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const MyContract = artifacts.require("MyContarct");
contract("MyContract", async ()=> { it("should transfer ether to specified address using Web3.js", async ()=>{ const instance = await MyContract.deployed();
const senderAddress = "0x8b2e442DE68731F84bb8DF9da2a923Fd1aC9E80a"; const receiverAddress = "0x502a65667b84f1f9E7C2E73D266b4a48783da25f"; const amountToSend = web3.utils.toWei("1", "ether");
const senderBalanceBefore = await web3.eth.getBalance(senderAddress);
await web3.eth.sendTransaction({ from: senderAddress, to: receiverAddress, value: amountToSend }); } }
|
转账给合约账户
在eth中,并不支持给合约用户转账,即使将合约地址带入如上方法,也会出现回滚,转账失败。
我们可以通过在合约中定义一个pay() public payable
函数,在调用时转账给合约账户
在test中
1 2 3 4 5 6 7 8 9
| const MyContract = artifacts.require("MyContract");
contract("MyContract", async()=>{ it("transfer to contract", async ()=> { const instance = await MyContract.deployed(); const amountToSend = web3.utils.toWei("1", "ether"); await instance.pay({from: "0x68090f81670Ba7D7F5f439004e02BB9683631AE8",value: amountToSend}) }) })
|
在gangache中查询交易,可以获得合约地址,并通过合约地址查询到对应的余额