Solidity
ethers.js (node.js) 呼叫支付的solidity函式
我知道你可以將乙太坊發送到智能合約,儘管當你這樣做時,你
sendTransaction
似乎並沒有在智能合約上指定一個函式。我不太明白這有什麼用。但是我不知道該怎麼做,就是將乙太坊發送到一個設置為應付的函式。我正在使用ethers.js並且可以創建合約,並呼叫可見(只讀)的函式沒問題,但我無法弄清楚如何將帶有交易的乙太坊發送到特定函式export const testContract = async (address, abi) => { const wei = Utils.parseEther("0.1") const url = "http://localhost:8545" const provider = new Providers.JsonRpcProvider(url) // Load the wallet to deploy the contract with const privateKey = "0x123" const wallet = new Wallet(privateKey, provider) var contract = new Contract(address, abi, wallet) const price = await contract.retrievePrice() console.log("price " + price) //logs the price set in the constructor when the contract was made (WORKS) const testAddress = await contract.isUser( "0x456" ) console.log("testAddress ", testAddress) //checks if the given address is a user on the contract (WORKS) const gasPrice = await provider.getGasPrice() console.log("gas price: ", gasPrice.toString()) //returns the price of gas from the network (WORKS) try { const addToUsers = await contract.requestAccess({ //call function to request access, from the current wallet (REVERTS) value: wei }) console.log("result of sending transaction ", addToUsers) } catch (error) { console.log("error.... ", error) //fires as the contract reverted the payment } }
contract.requestAccess
關於為什麼呼叫正在恢復我的任何幫助?我不太清楚如何呼叫特定函式並發送 Ether。謝謝!對評論的回應
好的,所以solidity合約中的函式如下所示:
function requestAccess() payable { require(msg.value == price, "Incorrect sum sent to contract"); _addUser(msg.sender); }
我註釋掉了要求,嘗試但仍然恢復。_addUser 來自我繼承的契約,看起來像
function _addUser(address account) internal { users.add(account); emit UserAdded(account); }
users
是Roles.Role private users;
並且位於父契約中contract Users { using Roles for Roles.Role;
從 openzeppelin “openzeppelin-solidity/contracts/access/Roles.sol” 導入
您可能會在評論中註意到,我無法弄清楚什麼對我不起作用,但不是“它有效,謝謝”答案的粉絲,這對其他人沒有幫助。所以我為任何正在尋找這個的人提供了一個關於要點的工作範例。只需要針對您的情況進行一些更改,但應該相對簡單。 https://gist.github.com/amlwwalker/89bc2c5a2b631527bb7def922b4c8306
引用自https://github.com/ethers-io/ethers.js/issues/563
let overrides = { // To convert Ether to Wei: value: ethers.utils.parseEther("1.0") // ether in this case MUST be a string // Or you can use Wei directly if you have that: // value: someBigNumber // value: 1234 // Note that using JavaScript numbers requires they are less than Number.MAX_SAFE_INTEGER // value: "1234567890" // value: "0x1234" // Or, promises are also supported: // value: provider.getBalance(addr) }; // Pass in the overrides as the 3rd parameter to your 2-parameter function: let tx = await exchangeContract.ethToTokenSwapOutput(tokens_bought, deadline, overrides);