eth向合约地址转账

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"); // 转账金额:1 ETH

// 获取发送者账户余额
const senderBalanceBefore = await web3.eth.getBalance(senderAddress);

// 使用 Web3.js 进行转账
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"); // 转账金额:1 ETH
await instance.pay({from: "0x68090f81670Ba7D7F5f439004e02BB9683631AE8",value: amountToSend})
})
})

在gangache中查询交易,可以获得合约地址,并通过合约地址查询到对应的余额