如何使用solidity和web3将以太币存入账户?
Posted
技术标签:
【中文标题】如何使用solidity和web3将以太币存入账户?【英文标题】:How to deposit ether to an account using solidity and web3? 【发布时间】:2019-10-17 06:18:36 【问题描述】:我正在构建一个示例智能合约。我正在尝试将以太币从一个帐户存入另一个帐户,但问题是金额已从发件人的帐户中扣除,但无法存入收件人的帐户。
这是我的合约代码:
pragma solidity ^0.5.0;
contract ApprovalContract
address public sender;
address public receiver;
function deposit(address _receiver) external payable
require(msg.value > 0);
sender = msg.sender;
receiver = _receiver;
address payable _rec = receiver.make_payable();
_rec.transfer(address(this).balance);
using address_make_payable for address;
library address_make_payable
function make_payable(address x) internal pure returns (address payable)
return address(uint160(x));
这是我的 web3 代码:
let ApprovalContract = new web3.eth.Contract(
abi,
"0xABd4495e3afc9E61Bbbf54620587aB4B48CEd7d3" //contract address
);
ApprovalContract.methods
.deposit("0xF33ca58CbD25bC0fFe5546Dc494E5c61C8D7fFc3")
.send(
from: "0x7186ffcf5ea764257fdbaefccb9472f054495d11",
gas: 100000,
value: web3.utils.toWei("1", "ether")
,
(err, res) =>
err
? console.log(`error: $err`)
: console.log(`Success: $res`)
);
【问题讨论】:
【参考方案1】:只需在您的智能合约中添加一些映射,例如mapping( address => uint256 ) balance
,这是您的固定智能合约:
pragma solidity ^0.5.0;
contract ApprovalContract
address payable owner = msg.sender;
mapping(address => uint256) balance;
function deposit() external payable
require(msg.value > 0);
sender = msg.sender;
deposited = msg.value;
receiver = owner;
balance[sender] = deposited;
receiver.transfer(deposited);
【讨论】:
我认为solidity代码是正确的,只需重新编码智能合约代码和web3并调试你的每一个代码。以上是关于如何使用solidity和web3将以太币存入账户?的主要内容,如果未能解决你的问题,请参考以下文章
《solidity学习笔记》chapter 2-solidity基础知识
如何获取以太坊合约和账户信息(使用geth和web3.py)
Web3与智能合约:开发一个简单的DApp并部署到以太坊测试网(Solidity+Hardhat+React)① 环境搭建