![](/img/trans.png)
[英]How to call Solidity Function to return Ether from Smart Contract?
[英]How to send variable amount of ether to smart contract from React front end?
我正在尝试从我的 React 前端向我的智能合约发送可变数量的以太币。 在混音中,只需选择数量并使用 function 发送,我就可以毫无问题地做到这一点
在我的前端,这是 function,其中 values.amount 是 100wei
const sendEth = async(e) => {
e.preventDefault()
try {
const { ethereum } = window;
if (ethereum) {
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const connectedContract = new ethers.Contract(CONTRACT_ADDRESS, escrowAbi.abi, signer);
let nftTxn = await connectedContract.depositEth(values.amount);
console.log("Mining...please wait.", nftTxn)
await nftTxn.wait();
console.log(`Mined, see transaction: https://rinkeby.etherscan.io/tx/${nftTxn.hash}`);
// console.log(connectedContract)
} else {
console.log("Ethereum object doesn't exist!");
}
} catch (error) {
console.log(error)
}
}
在我的智能合约中,这是我的 depositEth function - 但是 msg.value 是我想传递的参数,但我不能将它作为参数传递给这个 function?
仅供参考,在我的应用程序中,一旦您向合同支付 ETH,它就会发布 NFT。
function depositEth() public payable hasToken(address(this), nftAddress) {
require(msg.value == amountOwed, 'You ow more money');
buyerAddress = payable(msg.sender);
if(walletHoldsToken(address(this),nftAddress)) {
ERC721(nftAddress).safeTransferFrom(address(this), buyerAddress, tokenID);
}
}
所以我要问的是如何将 x 数量的 eth 发送到具有在前端定义的该值的合同?
在您的智能合约中定义一个 function 以返回所欠金额:
function getOwedAmount() public view returns (uint256) {
// i am assuming " amountOwed" is state variable, uint256
return amountOwed;
}
创建合约后。
const connectedContract = new ethers.Contract(CONTRACT_ADDRESS, escrowAbi.abi, signer)
获取拥有的数量
let owedAmount = await contract.getOwedAmount();
owedAmount=owedAmount.toString()
let transaction=await connectedContract.depositEth({value:owedAmount})
await transaction.wait();
由于depositEth
是可支付的,我们可以将最后一个参数作为 object 传递,指定我们发送了多少,solidity 会自动将该金额分配给msg.value
你的 depositEth depositEth()
function 需要 0 个参数,所以 JS 片段也需要传递 0 个参数。
在ethers
中有覆盖object ,总是在常规 function 参数之后传递(在您的情况下,在第一个位置,因为有 0 个参数),允许修改调用 function 的事务的某些字段,包括它的value
。
let nftTxn = await connectedContract.depositEth({
value: values.amount
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.