In some cases it is necessary to set the price of in the fiat currency such as Euro, USD and etc.
One possible way to achieve that is to use . The idea is simple — call the function from then it returns the price of one cent in ETH Wei.
Let’s consider an example from fiatcontract.com:
// returns $5.00 USD in ETH wei.
function FiveETHUSD() constant returns (uint256)
To calculate the price of one in Wei I introduced an EuroWei value:
1 Euro = 1e18 EuroWei (like 1 ETH = 1e18 Wei)
For example, if the current price of ETH is 100 Euro, then the following expressions are true:
1 cent = 0.0001 ETH = 1e14 Wei
1 cent = 0.01 Euro = 1e16 EuroWei
General form of expressions:
1e16 EuroWei = oneCent Wei
currentPrice EuroWei = x Wei
After applying the fundamental rule of proportions we could calculate the price of one in Wei:
x Wei = (currentPrice EuroWei / oneCent Wei) * 1e16 EuroWei
The code of our formula in Solidity:
public priceOfOneTokenInEuroWei = 1000000000000;
function getPrice() public returns(uint256 priceOfOneTokenInWei)
We could easily write the code for buy() and sell() functions using getPrice():
public priceOfOneTokenInEuroWei = 1000000000000;
function buy() payable public returns (uint256 amount)
//revenue — ether; amount — tokens
function sell(uint256 _amount) public payable returns(uint256 revenue)
Evidently, when user want to buy , then he/she send Ether to the smart contract’s function buy() and this function calculate how many he/she will receive based on price of one in Euro/USD.
When user want to sell , then he/she send to the smart contract’s function sell() and this function calculate how many Ethers he/she will receive based on price of one in Euro/USD.
The source code could be found in the of Social Decentralized (SDT)
Published at Fri, 29 Mar 2019 13:19:44 +0000