Solidity
Web3如何將乙太從客戶端Metamask發送到合約地址本機接收功能?
我想知道如何在本地彈出 MetaMask 視窗以將特定數量的乙太幣作為捐贈發送到已經定義的 SC 地址和 ABI?
短程式碼介紹:
pragma solidity >=0.7.0 <0.8.6; [...] receive() external payable minumum_donation_amount(msg.value) { OWNER.transfer(msg.value); donated_people[how_many_people_donated+1] = DonatedPeople(msg.sender, block.timestamp, msg.value); how_many_people_donated++; emit SubscribeDonatedPeople(msg.sender, block.timestamp, msg.value); } modifier minumum_donation_amount(uint256 amount) { require(amount >= 0.0005 ether, "The minumum donation amount is 0.0005 Ether"); _; } [...]
使用 web3 匿名函式成功地將數據從 SC 獲取到 JavaScript 控制台,如下所示:
(function () { CONTRACT.methods.donated_people(1).call().then( function( donated ) { console.log(donated); }); })();
我可以通過硬編碼 SC 地址和從/到地址來發送乙太幣。但是,我想直接從合約方法中獲取乙太幣到本機接收函式,該函式具有最小數量的修飾符。在 Remix 中,我們稱之為“低級互動”,如下所示:
任何想法如何在 web3 中實現與 Remix 中相同的結果?提前致謝!
這個例子效果很好。請注意,如果您想使用 SC 地址接收功能,您必須通過 CONTRACT.options.address
client_account = accounts[0]; // assuming master client addr function contribute_to_the_project() { const amount = "0.0004"; const amountToSend = web3.utils.toWei(amount, "ether"); // Convert to wei value web3.eth.sendTransaction({ from: client_account, to: CONTRACT.options.address, value: amountToSend }).then( function(tx) { ; console.log("Transaction: ", tx); }); }
該函式
web3.eth.sendTransaction
可用於直接轉賬到合約接收函式。web3.eth.sendTransaction({ from: USER_ADDRESS, to: CONTRACT_ADDRESS, value: AMOUNT_IN_WEI, gas: GAS_AMOUNT }) .then(function(receipt){ ... });