Reputation: 73
I'm trying to implement a solidity "purchase" function into web3. Ultimately, I want to have a button where a user would then have metamask open to send a fixed amount(1 ether for a simple example) to the smart contract in exchange for an ERC20 token. I've learned how to transfer tokens between two wallets, but now I'd like to go a step further and learn how to send Ether to receive an ERC20. This is the solidity "purchase" function I've been using:
function purchase(uint amount, uint tokens) public payable{
require (msg.value >= amount * 1 ether, "You must pay at least 1 ether per token");
balances[address (this)] -= tokens;
balances[msg.sender] += tokens;
Right now I've been using this with an Onclick button in conjunction with metamask to transfer ERC20's:
async function transfer() {
contract.methods.transfer("Address", "Token quantity").send({
from: "Address"});
Do you have any tips on how to go about making this Ether to ERC20 function in JS? Thank you!
Upvotes: 2
Views: 2360
Reputation: 113
There is insufficient information in the question. If you are asking how to call the purchase you have written in solidity then answer is as follow:
contract.methods.purchase("amount", "Token quantity").send({
from: "Address", value: ("amount"*"Token quantity"(in wei)) });
Upvotes: 2