Last updated
Last updated
Remember in the part 4 we talked about percentages. We said hundred percentage is 10,000 due to VM limitation using integers only. For future computation we need to store this constant inside the contract code :
Notice the type of HUNDRED_PERCENT
. It's the AssemblyScript's native u64
, not the mx-sdk-as's one. Instantiate classes statically may lead to issue when deploying the contract. Avoid it and prefers use primitive types when creating globals variables.
We didn't had a constructor
to our contract yet ! Time to add one inside the FlipContract
class :
The contract's constructor is called each time the contract is deployed or updated (if allowed to be). Here we simply initialise the storage.
We do not initialise maximumBet
and maximumBetPercent
here as they are relative to a token.
Next step, create the flip endpoint. Inside the FlipContract
class add the following method :
What does this code do ?
We need to ensure bet limits are not reached, hence we need to compute them.
Let's focus on the line const maximumBetPercentComputed = tokenReserve * maximumBetPercent / ManagedU64.fromValue(HUNDRED_PERCENT)
, math operations order is important since numbers cannot be decimals and divisions are trucated : 50 / 100 = 0
.
Suppose tokenReserve = 10, maximumBetPercent = 1000 and HUNDRED_PERCENT = 10_000, tokenReserve * maximumBetPercent / ManagedU64.fromValue(HUNDRED_PERCENT)
= 10 * 1000 / 10_000
= 10_000 / 10_000 = 1
Now the same computation in a different order : maximumBetPercent / ManagedU64.fromValue(HUNDRED_PERCENT) * tokenReserve
= 1000 / 10_000 * 10
= 0 * 10 = 0
Always multiply before dividing.
There is no max and min functions implemented for BigUint type at the moment. Theses are planned and this tutorial will updated when done.
We need to compute bounty and owners profits, after that can compute the real bet's amount.
This is simply done with the this.require
function.
Nothing special to say here, we get the last flip id, increment it and use all informations we have to create a new instance.
Then we update storage values : flipForId
, lastFlipId
and tokenReserve
. For the last one we only remove computed amount (instead of full payment amount) since owner profits and bounty are not realised yet.
The contract has the ability to initialise a flip, next step is to realise it !
Time to code the core contract logic