The Flip Smart Contract part 7 : Make the flip

Flips are initialised, time to make them

Remember, we built an endpoint that allow players to make a bet, but it's result should be computed in another transaction.

We said earlier that the bounty endpoint, not built yet, will compute all waiting bets results in a row. We'll write the bounty endpoint in the next part of this tutorial, now we'll focus on writing the function to generate result for a single bet.

Function's signature

Here is the function's signature, again inside the FlipContract class :

private makeFlip(
    bountyAddress: ManagedAddress,
    flip: Flip
): void {
    // Function code goes here
}

The key point is the private keyword. makeFlip is NOT an endpoint but an internal function we'll use in the future bounty endpoint.

bountyAddress is the address of the bounty caller endpoint. It is needed to send the incentive.

Making a function private ensure no one will be able to call it, forget it is a big security issue.

Function's body

Here is the full function :

private makeFlip(
    bountyAddress: ManagedAddress,
    flip: Flip
): void {
    const randomNumber = RandomnessSource.nextU8InRange(ManagedU8.fromValue(0), ManagedU8.fromValue(2))
    const isWin = randomNumber == ManagedU8.fromValue(1)

    this.send
        .direct(
            bountyAddress,
            flip.tokenIdentifier,
            flip.tokenNonce,
            flip.bounty
        )

    const profitIfWin = flip.amount * BigUint.fromU64(2)

    if (isWin) {
        this.send
            .direct(
                flip.playerAddress,
                flip.tokenIdentifier,
                flip.tokenNonce,
                profitIfWin
            )
    } else {
        let oldTokenReserve = this.tokenReserve(
            flip.tokenIdentifier,
            flip.tokenNonce
        ).get()

        this.tokenReserve(
            flip.tokenIdentifier,
            flip.tokenNonce
        ).set(oldTokenReserve + profitIfWin)
    }

    this.flipForId(flip.id).clear()
}

Nothing special in this function.

RandomnessSource is a class containing statics methods allowing you to generate random numbers. Remember that these numbers are predictables knowing current block random seed and transaction infos (sender, hash, ...).

Next up

The contract is almost finished, last thing we need to do is the bounty endpoint.

Last updated