Skip to content
CCPEDIAby Unity Nodes
App Development

Create contracts

2 posts247 views1 likesLast activity Jan 2023

  1. Tinglei_ZhangOP

    How can I create two contracts at the same time?

  2. WallaceKelly 1

    Hi, @Tinglei_Zhang! Welcome to the forums.

    I think “How can I create two contracts at the same time?” could also be asked as “How can I create two contracts within the same transaction?” Let us know if you have something else in mind.

    Here is an example:

        choice Split : [AssetId]
          controller owner
          do
            asset1 <- create this with name = name <> "1"
            asset2 <- create this with name = name <> "2"
            return [asset1, asset2]
    

    You can test the example yourself using the Asset template created by daml new TwoContracts. If you additionally exercise that choice within the script, you can see the transaction TX 3 that created the two assets:

    Not that you would generally split a TV! :grinning:

    Does that address your question?

    FullCode
    module Main where
    
    import Daml.Script
    
    type AssetId = ContractId Asset
    
    template Asset
      with
        issuer : Party
        owner  : Party
        name   : Text
      where
        ensure name /= ""
        signatory issuer
        observer owner
    
        choice Give : AssetId
          with
            newOwner : Party
          controller owner
          do create this with
               owner = newOwner
    
        choice Split : [AssetId]
          controller owner
          do
            asset1 <- create this with name = name <> "1"
            asset2 <- create this with name = name <> "2"
            return [asset1, asset2]
    
    
    setup : Script AssetId
    setup = script do
    -- user_setup_begin
      alice <- allocatePartyWithHint "Alice" (PartyIdHint "Alice")
      bob <- allocatePartyWithHint "Bob" (PartyIdHint "Bob")
      aliceId <- validateUserId "alice"
      bobId <- validateUserId "bob"
      createUser (User aliceId (Some alice)) [CanActAs alice]
      createUser (User bobId (Some bob)) [CanActAs bob]
    -- user_setup_end
    
      aliceTV <- submit alice do
        createCmd Asset with
          issuer = alice
          owner = alice
          name = "TV"
    
      bobTV <- submit alice do
        exerciseCmd aliceTV Give with newOwner = bob
    
      backToAlice <- submit bob do
        exerciseCmd bobTV Give with newOwner = alice
      
      [asset1, asset2] <- submit alice do
        exerciseCmd backToAlice Split
    
      return asset1