A simple mutual insurance contractΒΆ

type Storage= {
    participant: Array<string>,
    amount: int,
    owner: string
}

var M: Contract<Storage> = {}

function M:init()
    self.storage.participant=[]
    self.storage.amount=0
    self.storage.owner=caller_address --Record creator
    pprint("contract init")
    emit event("contract init")
end

function M:on_deposit(amount: int)
    local in_flag: bool = false  --Determine whether the contract has been involved
    for k,v in pairs(self.storage.participant) do
        if caller_address == v then
            in_flag = true
            break
        end
    end

    if in_flag == false then
        self.storage.participant[#self.storage.participant+1] = caller_address  --Record creator
    end

    self.storage.amount = tointeger(self.storage.amount+amount)              --Record the amount
    local deposit_info:string = tostring(caller_address).." transfered in,amount "..tostring(amount)..",sum "..tostring(get_contract_balance_amount()+amount)
    pprint("deposit info: ", deposit_info)
    emit event(deposit_info)
end

function M:handle(address:string)
    if self.storage.owner ~= caller_address then --Only allow creators to make claims
        pprint("caller_address is not the contract owner")
        pprint("caller_address: " , caller_address, " contract_owner_address: ", self.storage.owner)
        return
    end

    local in_flag: bool = false
    for k,v in pairs(self.storage.participant) do  --Traverse the list of participants and claim ones whose address is in the participant list.
        if address == v then
            in_flag = true
            local amount:int = math.floor(self.storage.amount/2)
            if amount > 10000000 then   --Maximum compensation is 100ACT
                amount = 10000000
            end
            local res=transfer_from_contract_to_address(address,"ACT",amount)
            self.storage.amount =self.storage.amount-amount
            pprint("amount: ", amount)
            local pay_info = "pay to "..address..""..tostring(amount)
            pprint("pay info: ", pay_info)
            emit event("pay to "..address..""..tostring(amount))
        end
    end

    if in_flag == false then
        pprint("caller ", caller_address, " did not take part in this contract")
    end
end

function M:get_balance()
    pprint("contract balance: ", self.storage.amount)
end

function M:get_participator()
    pprint("contract participator:")
    for k,v in pairs(self.storage.participant) do
        pprint(v)
    end
end

return M