I saw this code but I didn't understand how he calculated the interest rate . this contract mint tokens as an interest and transfer them to users who deposited to the contract (calculated according to the Hold time) I will be grateful if anyone can help ?
https://github.com/dappuniversity/dbank/blob/master/src/contracts/dBank.sol
//check user's hodl time
uint depositTime = block.timestamp - depositStart[msg.sender];
**//31668017 - interest(10% APY) per second for min. deposit amount (0.01 ETH), cuz:
//1e15(10% of 0.01 ETH) / 31577600 (seconds in 365.25 days)
//(etherBalanceOf[msg.sender] / 1e16) - calc. how much higher interest will be (based on deposit), e.g.:
//for min. deposit (0.01 ETH), (etherBalanceOf[msg.sender] / 1e16) = 1 (the same, 31668017/s)
//for deposit 0.02 ETH, (etherBalanceOf[msg.sender] / 1e16) = 2 (doubled, (2*31668017)/s)
uint interestPerSecond = 31668017 * (etherBalanceOf[msg.sender] / 1e16);
uint interest = interestPerSecond * depositTime;**
//send funds to user
msg.sender.transfer(etherBalanceOf[msg.sender]); //eth back to user
token.mint(msg.sender, interest); //interest to user
depositTime is the number of seconds from the last deposit.
interestPerSecond is calculated from the current ETH balance of the user deposited to the contract
And the interest amount is a simple multiplication between the two above.
Example:
The user has deposited 1 ETH exactly 30 days ago (2,592,000 seconds). This makes the
depositTime == 2592000
interestPerSecond == 31668017 * (etherBalanceOf[msg.sender] / 1e16) == 31668017 * (1000000000000000000 / 1e16) == 31668017 * 100 == 3166801700
interest == interestPerSecond * depositTime == 2592000 * 3166801700 == 8208350006400000
Now, the linked contract imports another contract - Token.sol, that imports the OpenZeppelin ERC20.sol.
The imported ERC20.sol defines 18 decimal places. So you need to account for 18 decimals to get the total amount of tokens that you get as the interest.
8208350006400000 / 1e18 == 0.00820835
So if you deposit 1 ETH 30 days ago, you get 0.00820835 of the token as an interest.
Related
According to the "Liqudity Math in uniswap v3", the liqudity of a position should be:
L = amt0 * (sqrt(upper) * sqrt(cprice)) / (sqrt(upper) - sqrt(cprice))
or
L = amt1 / (sqrt(cprice) - sqrt(lower))
I tried to calculate the liquidity of the below position on Arbitrum:
The nft token ID of the position is 69171, so I can get the liqudity by calling the contract(0xC36442b4a4522E871399CD717aBDD847Ab11FE88) on https://arbiscan.io
You can see it shows the liqudity is 50242219347523, and we can do more unit convertion:
Now I try to calcuate this number with the uniswap V3 math:
This is the output:
As we can see, the code output is very similar to the contract output, but if we look carefully, we will find the unit seems to be different. I know the unit of the contract ouput should be 'wei', but I don't know what the unit of the code results is. Can anybody help? Thanks.
I checked that position and pool. Best to query the current price from the pool's contract, for quick look the UI can be found at https://info.uniswap.org/#/arbitrum/pools/0x2f5e87c9312fa29aed5c179e456625d79015299c
The current price is shown as 11.9011 ETH per BTC, and there are 0.3122 BTC and 1.466 ETH in the pool. This gives:
price = 11.9011 * (1e18 / 1e8)
x = 0.3122 * 1e8
y = 1.466 * 1e18
The tick range of the position No. 69171 is 253300 to 259900. Use these values to calculate sp = sqrt(price) and the square roots of the price range boundaries, and from them, the liquidity:
sp = price ** 0.5
sa = 1.0001 ** (253300 // 2)
sb = 1.0001 ** (259900 // 2)
Lx = x * sp * sb / (sb - sp)
Ly = y / (sp - sa)
L = min(Lx, Ly)
The result Lx is 49905251975363.266 and Ly is 51071435112054.96. The Etherscan info shows liquidity L=50242219347523, in between these two values, which have a few % difference. A few % is an acceptable error given the imprecise input values used in this calculation; the UI shows the price and amount values in a rounded format.
I'm looking to calculate and plot the funding rate of Binance BTCUSDT Perpetual and have come across the following documentation page: https://www.binance.com/en/support/faq/360033525031
It states:
The Funding Rate formula:
"Funding Rate (F) = Average Premium Index (P) + clamp (interest rate - Premium Index (P), 0.05%, -0.05%)"
I'm obtaining the "Premium Index" just fine, just with "p = request.security("BINANCE:BTCUSDT_PREMIUM", "", close)*100"
However I'm currently struggling with how to obtain the:
"Time-to-funding weighted Average of Premium Index " which apparently is calculated with
"Average Premium Index (P) = (1 * Premium_Index_1 + 2 * Premium_Index_2 + 3 * Premium_Index_3 +···+·480 * Premium_index_480)/(1+2+3+···+480)"
(the funding period for Binance is 8 hours hence the average over 480 minutes)
My exact question is, how do I backtrack to the last funding timestamp of 00:00 / 08:00 / 16:00, then obtain an array / series data of the premium index at each of the last 480 minutes, so that I can then iterate over it to use the above formula for the time weighted average?
Thank you very much for any advice in advance. My apologies if the answer is obvious I'm very new to Pine Script.
I believe you can obtain the time weighted average premium like so:
premium = request.security("BINANCE:BTCUSDT_PREMIUM", "1", close)
new_funding_period = ta.change(time("480")) != 0
var int n = na
var float premium_sum = na
var int n_sum = na
if new_funding_period
n := 1
premium_sum := premium
n_sum := 1
else
n += 1
premium_sum += premium * n
n_sum += n
predicted_TWAP = premium_sum / n_sum
current_TWAP = ta.valuewhen(new_funding_period, predicted_TWAP[1], 0)
However, you are limited to performing the calculation on a 1 minute chart to obtain accurate results due to being unable to reliably retrieve the values from a security call from a lower timeframe when the chart is set to a higher timeframe than 1 minute.
I get the following error when using code for an extension, I'm not sure if they're asking to just use a different operator or modify the values in the expression based on an internet search.
Error: % is unavailable: Use truncatingRemainder instead
Extension code:
extension CMTime {
var durationText:String {
let totalSeconds = CMTimeGetSeconds(self)
let hours:Int = Int(totalSeconds / 3600)
let minutes:Int = Int(totalSeconds % 3600 / 60)
let seconds:Int = Int(totalSeconds % 60)
if hours > 0 {
return String(format: "%i:%02i:%02i", hours, minutes, seconds)
} else {
return String(format: "%02i:%02i", minutes, seconds)
}
}
}
The error(s) occur when setting the minutes and seconds variables.
CMTimeGetSeconds() returns a floating point number (Float64 aka
Double). In Swift 2 you could compute the
remainder of a floating point division as
let rem = 2.5 % 1.1
print(rem) // 0.3
In Swift 3 this is done with
let rem = 2.5.truncatingRemainder(dividingBy: 1.1)
print(rem) // 0.3
Applied to your code:
let totalSeconds = CMTimeGetSeconds(self)
let hours = Int(totalSeconds / 3600)
let minutes = Int((totalSeconds.truncatingRemainder(dividingBy: 3600)) / 60)
let seconds = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
However, in this particular case it is easier to convert the duration
to an integer in the first place:
let totalSeconds = Int(CMTimeGetSeconds(self)) // Truncate to integer
// Or:
let totalSeconds = lrint(CMTimeGetSeconds(self)) // Round to nearest integer
Then the next lines simplify to
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let seconds = totalSeconds % 60
The % modulus operator is defined only for integer types. For floating-point types, you need to be more specific about the kind of IEEE 754 division/remainder behavior you want, so you have to call a method: either remainder or truncatingRemainder. (If you're doing floating-point math you actually need to care about this, and lots of other stuff, or you can get unexpected / bad results.)
If you actually intend to do integer modulus, you need to convert the return value of CMTimeGetSeconds to an integer before using %. (Note that if you do, you'll lop off the fractional seconds... depending on where you're using CMTime that may be important. Do you want minutes:seconds:frames, for example?)
Depending on how you want to present CMTime values in your UI, it might be better to extract the seconds value and pass it to NSDateFormatter or NSDateComponentsFormatter so you get appropriate locale support.
Bring back the simple modulo syntax in swift 3:
This syntax was actually suggested on Apples official swift mailing list here but for some reason they opted for a less elegant syntax.
infix operator %%/*<--infix operator is required for custom infix char combos*/
/**
* Brings back simple modulo syntax (was removed in swift 3)
* Calculates the remainder of expression1 divided by expression2
* The sign of the modulo result matches the sign of the dividend (the first number). For example, -4 % 3 and -4 % -3 both evaluate to -1
* EXAMPLE:
* print(12 %% 5) // 2
* print(4.3 %% 2.1) // 0.0999999999999996
* print(4 %% 4) // 0
* NOTE: The first print returns 2, rather than 12/5 or 2.4, because the modulo (%) operator returns only the remainder. The second trace returns 0.0999999999999996 instead of the expected 0.1 because of the limitations of floating-point accuracy in binary computing.
* NOTE: Int's can still use single %
* NOTE: there is also .remainder which supports returning negatives as oppose to truncatingRemainder (aka the old %) which returns only positive.
*/
public func %% (left:CGFloat, right:CGFloat) -> CGFloat {
return left.truncatingRemainder(dividingBy: right)
}
This simple swift 3 migration tip is part of a more comprehensive swift 3 migration guide with many insights (35k loc / 8-days of migration) http://eon.codes/blog/2017/01/12/swift-3-migration/
There's no need to create a separate modulo operator for floating point numbers, unless you think it makes the code safer. You can overload the % operator to accept floating point numbers like so:
func %<N: BinaryFloatingPoint>(lhs: N, rhs: N) -> N {
lhs.truncatingRemainder(dividingBy: rhs)
}
Usage
let a: Float80 = 10
let b: Float80 = 3
print(a % b)
You can now use % with any two floating point numbers of the same tye.
I found that the following works in Swift 3:
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(totalSeconds) % 60
where totalSeconds is a TimeInterval (Double).
I see an interesting score number from the leader board of one of my apps: 2,147,483,647.
This number happens to be 2^23 -1 and it's one of known double Mersenne primes.
Here is the code how I calculate game score:
float highestScore = 10000;
float factor1 = powf(0.90, (colNumber == 7 ? 0 : 1));
float factor2 = powf(0.90, (rowNumber == 8 ? 0 : 1));
float factor3 = powf(0.9, (size - 2));
float factor4 = rotationOn ? 1 : 0.33;
float factor5 = powf(0.8, hintCount);
float factor6 = pow(0.95, ((int)(tick / 30)));
float factor7 = pow(0.90, letterNum);
theScore = (int) (highestScore * factor1 * factor2 * factor3 * factor4 * factor5 * factor6 * factor7);
//sometime later but before reporting game score to leader board
int64_t score64t = (int64_t)theScore;
I don't know why a big number score is reported (actually two cases of this big number score), but I wonder if this relates to jailbreak devices. How can I remove this score from the leaderboard?
Jailbroken devices can cheat game center. There is an app for jailbroken devices that let the user choose the score that is sent. It is a problem that happen with all games. In game center configurations you can set the maximum possible score to mitigate this problem, but cheaters will still be able to score that value, even if they didn't really did that score.
You can block scores by going to iTunnes Connect -> Manager Your Apps -> select the app you -> Manage Game Center -> Manage Score and Players -> Click Manage in the Manage Top Scores column
INFORMIX-SQL 7.3 Perform Screen:
Suppose I have a customer who wants to pay a $100 (7% tax included), what logic can I use
so that when the cashier clerk enters $100 in the tax included sale amount, it will
calculate the sale price and tax so that it adds up to $100.
I have the following 3 field tags in my Perform screen:
sprice = transaction.sale_price;
stax = transaction.sale_tax;
stotal = transaction.sale_total;
after editadd of transaction.sale_price
?...what goes here...?
If your problem is the formula then sprice = stotal * 100 / (100 + stax).
For example
$12345 * 100 / (100 + 7) = $11537.38
and adding 7% to $11537.38 gives you $12345.
Note of course that it may be impossible to find an exact amount of pennies that after adding a tax will give you a prescribed total.
To calculate disaggregated cost:
sprice = stotal / (1 + .07)
stax = sprice * .07
Finally round both figures. Depending on the rounding algorithm you may need to apply a penny offset if the resulting rounding operation is off by a cent so that all figures add up.
Basic algebra arithmetic:
93% = 93 per centum which is Latin for 93/100 = 0.93
Total receipt = p
Sale price + Tax = p
Sale price = 0.93p
Tax = 0.07p
4gl form:
sprice = transaction.sale_price,TYPE MONEY(7,2);
stax = transaction.sale_tax,TYPE MONEY(7,2);
stotal = transaction.sale_total,TYPE MONEY(7,2);
.....
INPUT ....
AFTER FIELD stotal
IF transaction.sale_total is NULL THEN
ERROR "Please enter total sale amount"
ELSE
LET transaction.sale_tax = 0.07 * transaction.sale_total
LET transaction.sale_price = 0.93 * transaction.sale_total
ENDIF