Initial commit

Signed-off-by: Balazs Toldi <balazs@toldi.eu>
This commit is contained in:
Balazs Toldi 2022-06-01 09:11:48 +02:00
commit 9a9df60267
Signed by: Bazsalanszky
GPG key ID: 6C7D440036F99D58
8 changed files with 877 additions and 0 deletions

60
contracts/Exchange.sol Normal file
View file

@ -0,0 +1,60 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Exchange is Ownable {
IERC20 _token;
uint256 price = 10;
uint256 priceDivider = 1;
// token = MyToken's contract address
constructor(address token) {
_token = IERC20(token);
}
function setPrice(uint256 _price) public onlyOwner(){
price = _price;
}
function getPrice() public view returns (uint256) {
return price;
}
function setPriceDivider(uint256 _priceDivider) public onlyOwner() {
priceDivider = _priceDivider;
}
function getPriceDivider() public view returns (uint256) {
return priceDivider;
}
// Modifier to check token allowance
modifier checkAllowance(uint amount) {
require(_token.allowance(msg.sender, address(this)) >= amount, "Error");
_;
}
// In your case, Account A must to call this function and then deposit an amount of tokens
function sellTokens(uint _amount) public checkAllowance(_amount) {
_token.transferFrom(msg.sender, address(this), _amount);
payable(msg.sender).transfer(_amount*priceDivider/price);
}
function depositTokens(uint _amount) public checkAllowance(_amount) {
_token.transferFrom(msg.sender, address(this), _amount);
}
function buyToken() public payable {
require(msg.value >= 10000000000000000);
uint256 tokenAmount = msg.value / priceDivider * price;
require(getSmartContractBalance() >= tokenAmount);
_token.transfer(msg.sender,tokenAmount);
}
// Allow you to show how many tokens owns this smart contract
function getSmartContractBalance() public view returns(uint) {
return _token.balanceOf(address(this));
}
}

19
contracts/Migrations.sol Normal file
View file

@ -0,0 +1,19 @@
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract Migrations {
address public owner = msg.sender;
uint public last_completed_migration;
modifier restricted() {
require(
msg.sender == owner,
"This function is restricted to the contract's owner"
);
_;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}

257
dapp/index.html Normal file
View file

@ -0,0 +1,257 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>⇋ BMEther-E-HUF Swap</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.6.1/web3.min.js"
integrity="sha512-5erpERW8MxcHDF7Xea9eBQPiRtxbse70pFcaHJuOhdEBQeAxGQjUwgJbuBDWve+xP/u5IoJbKjyJk50qCnMD7A=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="container">
<h1>⇋ BMEther-E-HUF Swap</h1>
<div id="loginForm">
<form>
<div class="mb-3">
<h3>Login</h3>
<label for="address" class="form-label">Address</label>
<input type="text" class="form-control" id="address" aria-describedby="address" disabled>
<div id="loginHelp" class="form-text">Connect your metamask wallet to swap founds ⇋</div>
</div>
</form>
<div class="mb-3">
<button class="col mx-2 btn btn-primary enableEthereumButton">Enable Ethereum</button>
</div>
</div>
<div class="mb-3" id="etherToToken" style="display: none;">
<form>
<div class="mb-3">
<h3>Swap BMEther to E-HUF</h3>
<label for="amount" class="form-label">BMEther Amount</label>
<input type="number" class="form-control" id="toToken" aria-describedby="amount" value="0">
<div id="loginHelp" class="form-text">The amount of BMEther you want to swap for E-HUF ⇋</div>
<label for="tokenAmount1" class="form-label">E-HUF Amount</label>
<input type="number" class="form-control" id="tokenAmount1" aria-describedby="tokenAmount" disabled>
<div id="loginHelp" class="form-text">The amount of E-HUF you will receive after the swap</div>
</div>
</form>
<div class="mb-3">
<button class="col mx-2 btn btn-success" id="buyToken">Buy tokens</button>
</div>
<form>
<div class="mb-3">
<h3>Swap E-HUF to BMEther</h3>
<label for="amount" class="form-label">E-HUF Amount</label>
<input type="number" class="form-control" id="toEther" aria-describedby="amount" value="0">
<div id="loginHelp" class="form-text">The amount of E-HUF you want to swap for BMEther ⇋</div>
<label for="tokenAmount2" class="form-label">BMEther Amount</label>
<input type="number" class="form-control" id="tokenAmount2" aria-describedby="tokenAmount" disabled>
<div id="loginHelp" class="form-text">The amount of BMEther you will receive after the swap</div>
</div>
</form>
<div class="mb-3">
<button class="col mx-2 btn btn-primary" id="approveToken" disabled>Approve</button>
<button class="col mx-2 btn btn-danger" id="sellToken" disabled>Sell token</button>
</div>
</div>
</div>
<script src="swap.js"></script>
<script>
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
}
let contract;
let tokenContract;
var web3;
let accounts = [];
const ethereumButton = document.querySelector('.enableEthereumButton');
const toToken = document.querySelector('#toToken');
const tokenAmount1 = document.querySelector('#tokenAmount1');
const buyButton = document.querySelector('#buyToken');
const toEther = document.querySelector('#toEther');
const tokenAmount2 = document.querySelector('#tokenAmount2');
const approveButton = document.querySelector('#approveToken');
const sellButton = document.querySelector('#sellToken');
ethereumButton.addEventListener('click', () => {
getAccount();
});
buyButton.addEventListener('click', () => {
updateTokenPrice1();
buyToken();
});
approveButton.addEventListener('click', () => {
updateTokenPrice2();
approveSwap();
});
sellButton.addEventListener('click', () => {
updateTokenPrice2();
sellToken();
});
async function approveSwap() {
let sellAmount = toEther.value;
if (isNumeric(sellAmount)) {
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
document.getElementById("address").value = accounts[0];
let allowed = new web3.utils.BN(await tokenContract.methods.allowance(accounts[0], ContractAddress).call());
let sellWei = new web3.utils.BN(await web3.utils.toWei(sellAmount, 'ether'));
if (allowed.lt(sellWei)) {
sellButton.disabled = true;
await tokenContract.methods.approve(ContractAddress, sellWei).send({ from: accounts[0] });
} else {
sellButton.disabled = false;
}
}
}
async function buyToken() {
let buyAmount = toToken.value;
if (isNumeric(buyAmount)) {
let price = await contract.methods.getPrice().call();
let priceDivider = await contract.methods.getPriceDivider().call();
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
document.getElementById("address").value = accounts[0];
await contract.methods.buyToken().send({ from: accounts[0], value: buyAmount * 10 ** 18 });
}
}
async function sellToken() {
let sellAmount = toEther.value;
console.log(sellAmount);
if (isNumeric(sellAmount)) {
let price = await contract.methods.getPrice().call();
let priceDivider = await contract.methods.getPriceDivider().call();
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
document.getElementById("address").value = accounts[0];
let allowed = new web3.utils.BN(await tokenContract.methods.allowance(accounts[0], ContractAddress).call());
let sellWei = new web3.utils.BN(await web3.utils.toWei(sellAmount, 'ether'));
if (allowed.gte(sellWei)) {
await contract.methods.sellTokens(sellWei).send({ from: accounts[0] });
} else {
sellButton.disabled = true;
}
} else {
sellButton.disabled = true;
approveButton.disabled = true;
}
}
toToken.addEventListener('change', () => {
updateTokenPrice1();
})
toEther.addEventListener('change', () => {
updateTokenPrice2();
})
async function getAccount() {
await registerTestnet();
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
document.getElementById("address").value = accounts[0];
hideLogin();
showSwap();
if(contract == undefined){
initContracts();
}
}
async function updateTokenPrice1() {
if (isNumeric(toToken.value)) {
buyButton.disabled = false;
} else {
buyButton.disabled = true;
}
let price = await contract.methods.getPrice().call();
let priceDivider = await contract.methods.getPriceDivider().call();
tokenAmount1.value = toToken.value * price / priceDivider;
}
async function updateTokenPrice2() {
if (isNumeric(toEther.value)) {
approveButton.disabled = false;
let price = await contract.methods.getPrice().call();
let priceDivider = await contract.methods.getPriceDivider().call();
let sellAmountEther = toEther.value / price * priceDivider * 10 ** 18;
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
document.getElementById("address").value = accounts[0];
let allowed = await tokenContract.methods.allowance(accounts[0], ContractAddress);
tokenAmount2.value = toEther.value / price * priceDivider;
sellButton.disabled = allowed < web3.utils.toWei(toEther.value,'ether');
} else {
approveButton.disabled = true;
sellButton.disabled = true;
}
}
function showLogin() {
document.querySelector("#loginForm").style.display = 'block';
}
function hideLogin() {
document.querySelector("#loginForm").style.display = 'none';
}
function showSwap() {
document.querySelector("#etherToToken").style.display = 'block';
}
function hideSwap() {
document.querySelector("#etherToToken").style.display = 'none';
}
function initContracts() {
contract = new web3.eth.Contract(ContractABI, ContractAddress);
tokenContract = new web3.eth.Contract(ERC20ABI, tokenAddress);
}
window.addEventListener("load", function () {
if (typeof web3 !== "undefined") {
web3 = new Web3(web3.currentProvider);
//console.log(web3);
initContracts();
web3.eth.getAccounts().then(account => {
console.log(account);
document.getElementById("address").value = account[0];
hideLogin();
showSwap();
});
} else {
console.log("No web3? You should consider trying MetaMask!");
}
});
</script>
</body>
</html>

414
dapp/swap.js Normal file
View file

@ -0,0 +1,414 @@
const ContractABI = JSON.parse(`[
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "previousOwner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"inputs": [],
"name": "buyToken",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "depositTokens",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "renounceOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_amount",
"type": "uint256"
}
],
"name": "sellTokens",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_price",
"type": "uint256"
}
],
"name": "setPrice",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "_priceDivider",
"type": "uint256"
}
],
"name": "setPriceDivider",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "token",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getPrice",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getPriceDivider",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getSmartContractBalance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
}
]`);
const ERC20ABI = JSON.parse(`[
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "to",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "account",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "from",
"type": "address"
},
{
"internalType": "address",
"name": "to",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
}
]`);
const ContractAddress = "0x124375e24Ce464074B3f3Fe50B26839fCCbD49d7";
const tokenAddress = '0x6C954E9355CBeFb21E1523B3784F162BbBF2e64e';
const tokenSymbol = 'EHUF';
const tokenDecimals = 18;
const tokenImage = 'https://en.numista.com/catalogue/photos/hongrie/5f2ad53298dae2.07716248-original.jpg';
function registerToken() {
const wasAdded = ethereum.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20', // Initially only supports ERC20, but eventually more!
options: {
address: tokenAddress, // The address that the token is at.
symbol: tokenSymbol, // A ticker symbol or shorthand, up to 5 chars.
decimals: tokenDecimals, // The number of decimals in the token
image: tokenImage, // A string url of the token logo
},
},
});
}
async function registerTestnet() {
try {
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x9C85' }],
});
} catch (switchError) {
// This error code indicates that the chain has not been added to MetaMask.
if (switchError.code === 4902) {
try {
await ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0x9C85',
chainName: 'BME Testnet',
rpcUrls: ['https://testnet.toldi.eu'],
iconUrls: ['https://www.bme.hu/sites/all/themes/foo/logo.png'],
nativeCurrency: {
name: "BMEther",
symbol: "BME", // 2-6 characters long
decimals: 18
}
},
],
});
} catch (addError) {
// handle "add" error
}
}
// handle other "switch" errors
}
}
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}

View file

@ -0,0 +1,5 @@
const Migrations = artifacts.require("Migrations");
module.exports = function (deployer) {
deployer.deploy(Migrations);
};

6
package-lock.json generated Normal file
View file

@ -0,0 +1,6 @@
{
"name": "Swap",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

0
test/.gitkeep Normal file
View file

116
truffle-config.js Normal file
View file

@ -0,0 +1,116 @@
/**
* Use this file to configure your truffle project. It's seeded with some
* common settings for different networks and features like migrations,
* compilation and testing. Uncomment the ones you need or modify
* them to suit your project as necessary.
*
* More information about configuration can be found at:
*
* https://trufflesuite.com/docs/truffle/reference/configuration
*
* To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
* to sign your transactions before they're sent to a remote public node. Infura accounts
* are available for free at: infura.io/register.
*
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
* phrase from a file you've .gitignored so it doesn't accidentally become public.
*
*/
// const HDWalletProvider = require('@truffle/hdwallet-provider');
//
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();
module.exports = {
/**
* Networks define how you connect to your ethereum client and let you set the
* defaults web3 uses to send transactions. If you don't specify one truffle
* will spin up a development blockchain for you on port 9545 when you
* run `develop` or `test`. You can ask a truffle command to use a specific
* network from the command line, e.g
*
* $ truffle test --network <network-name>
*/
networks: {
// Useful for testing. The `development` name is special - truffle uses it by default
// if it's defined here and no other network is specified at the command line.
// You should run a client (like ganache, geth, or parity) in a separate terminal
// tab if you use this network and you must also set the `host`, `port` and `network_id`
// options below to some value.
//
// development: {
// host: "127.0.0.1", // Localhost (default: none)
// port: 8545, // Standard Ethereum port (default: none)
// network_id: "*", // Any network (default: none)
// },
// Another network with more advanced options...
// advanced: {
// port: 8777, // Custom port
// network_id: 1342, // Custom network
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
// from: <address>, // Account to send txs from (default: accounts[0])
// websocket: true // Enable EventEmitter interface for web3 (default: false)
// },
// Useful for deploying to a public network.
// NB: It's important to wrap the provider as a function.
// ropsten: {
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
// network_id: 3, // Ropsten's id
// gas: 5500000, // Ropsten has a lower block limit than mainnet
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
// },
// Useful for private networks
// private: {
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
// network_id: 2111, // This network is yours, in the cloud.
// production: true // Treats this network as if it was a public net. (default: false)
// }
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
version: "0.8.13", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
// settings: { // See the solidity docs for advice about optimization and evmVersion
// optimizer: {
// enabled: false,
// runs: 200
// },
// evmVersion: "byzantium"
// }
}
},
// Truffle DB is currently disabled by default; to enable it, change enabled:
// false to enabled: true. The default storage location can also be
// overridden by specifying the adapter settings, as shown in the commented code below.
//
// NOTE: It is not possible to migrate your contracts to truffle DB and you should
// make a backup of your artifacts to a safe location before enabling this feature.
//
// After you backed up your artifacts you can utilize db by running migrate as follows:
// $ truffle migrate --reset --compile-all
//
// db: {
// enabled: false,
// host: "127.0.0.1",
// adapter: {
// name: "sqlite",
// settings: {
// directory: ".db"
// }
// }
// }
};