Repository navigation
Expand file tree
/
Copy pathdex.sol
More file actions
65 lines (51 loc) · 2.07 KB
/
Copy pathdex.sol
File metadata and controls
65 lines (51 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract DEX {
// Mapping from asset IDs to asset info
mapping (uint => Asset) public assets;
// Struct to store asset info
struct Asset {
address owner;
uint balance;
}
// Mapping from user addresses to their token balances
mapping (address => mapping (uint => uint)) public balances;
// Function to add a new asset to the exchange
function addAsset(uint id, uint initialSupply) public {
require(assets[id].balance == 0, "Asset already exists.");
// Set the initial asset info
assets[id] = Asset({
owner: msg.sender,
balance: initialSupply
});
// Set the initial balance for the asset owner
balances[msg.sender][id] = initialSupply;
}
// Function to buy an asset
function buyAsset(uint id, uint amount) public payable {
require(amount > 0, "Amount must be greater than zero.");
require(assets[id].balance >= amount, "Insufficient asset supply.");
// Calculate the total cost of the purchase
uint cost = amount * assets[id].price;
require(msg.value >= cost, "Insufficient funds.");
// Transfer the assets to the buyer
assets[id].owner.transfer(amount);
balances[msg.sender][id] += amount;
// Transfer the funds to the asset owner
assets[id].owner.transfer(cost);
}
// Function to sell an asset
function sellAsset(uint id, uint amount) public {
require(amount > 0, "Amount must be greater than zero.");
require(balances[msg.sender][id] >= amount, "Insufficient asset balance.");
// Transfer the assets to the exchange
assets[id].owner.transfer(amount);
balances[msg.sender][id] -= amount;
// Transfer the funds to the seller
msg.sender.transfer(amount * assets[id].price);
}
// Function to get the balance of an asset for a given user
function getBalance(address user, uint id) public view returns (uint) {
return balances[user][id];
}
}