Search code examples
daml

Unable to update contract state when trying to execute choice Disperse or Repay


Trying to create a loan system which have fasility of loan approval, disbursement, and repayment using DAML contracts

While exercising the choice Disperse and Repay, I'm changing status accordingly to Repaid or Dispersed.

But when I ran the test scenarios i'm not able to see the updated state of the contract.

It only shows the inital created state.

I have tried DAML trigers but no luck.

Attacking github repo link for code refrence.

Project Link


Solution

  • You have to carefully distinguish between value types like Loan and persisted contracts which need to be explicitly created using the create keyword.

    Let's take for example this choice:

        -- Choice to disburse tokens to the borrower
        nonconsuming choice Disburse : Loan
          controller bank
          do
            debug "Disbursing tokens"
            debug "Tokens disbursed"
            -- Return the updated loan contract with the new disbursed amount
            return this with disbursedAmount = amount, status = Disbursed
    

    The keyword nonconsuming means that calling Disburse will not consume the current loan with status Approved, but leave it in place. You'll likely want a preconsuming choice, which archives the contract at the beginning of the call, or you can manually insert an archive self at the beginning of the body.

    this with disbursedAmount = amount, status = Disbursed is a value of type Loan, which matches the return type of the choice: Disburse : Loan. What you want to do is to create a contract with that value, and return a reference to that contract.

    cid <- create this with disbursedAmount = amount, status = Disbursed
    return cid
    

    Your return type has to change accordingly to a ContractId Loan. Summing up then, your choice should probably look like this:

        -- Choice to disburse tokens to the borrower
        nonconsuming choice Disburse : ContractId Loan
          controller bank
          do
            archive self
            debug "Disbursing tokens"
            debug "Tokens disbursed"
            -- Return the updated loan contract with the new disbursed amount
            cid <- create this with disbursedAmount = amount, status = Disbursed
            return cid
    

    Try applying this pattern throughout your project. It should have the desired effect.