Developing smart contracts with Visual Studio Code extension

Important: You are not looking at the latest product documentation. Make sure you are reading the documentation that matches the version of the software that you are using. Switch to product version 2.1.3, 2.5, 2.5.1, 2.5.2 (latest)

The IBM® Blockchain Platform Developer Tools provide an environment within Visual Studio Code for developing, packaging, and testing smart contracts. You can use the tools to create your smart contract project and get started developing your business logic. You can then use it to test your smart contract before you deploy the smart contract to the IBM Blockchain Platform. This tutorial describes how to install and use the VS Code extension.

Typical smart contract development workflow
Figure 1. Typical smart contract development workflow with IBM Blockchain Platform VS Code extension

The IBM Blockchain Platform extension works seamlessly with any instance of the IBM Blockchain Platform that uses Hyperledger Fabric versions 1.4 and later. This tutorial is oriented toward users of the high-level Fabric smart contract programming model. If you are using low-level smart contract APIs, you can find additional instructions in the IBM Blockchain Platform extension documentation. You can also debug smart contracts by running a local Fabric peer in devmode. For more information, see the Chaincode for developers tutorial in the Fabric documentation.

Step one: Install IBM Blockchain Platform VS Code extension for free

Before you install the IBM Blockchain Platform VS Code extension on your local system, you must complete the prerequisites.

Prerequisites

Considerations if you are developing Java smart contracts:

If you are using Windows, you also must ensure the following:

If you installed Node and npm by using a manager such as 'nvm' or 'nodenv', you need to set the default or global version. You can then restart VS Code for the version to be detected by the Prerequisites page.

Install the extension

  1. Go to the Visual Studio Code extension marketplace page or search for IBM Blockchain Platform in the extensions panel within Visual Studio Code.
  2. Click Install.
  3. Restart Visual Studio Code to complete installation of the extension.

After the installation, you can use the IBM Blockchain icon on the left side of VS Code to open the IBM Blockchain Platform panel.

IBM Blockchain icon
Figure 2. IBM Blockchain icon in VS Code

The extension also adds new commands to the Visual Studio Code command palette. You can use the command palette to complete many of the operations that are explained in details in this guide.

Guided tutorials in VS Code

The IBM Blockchain Platform extension provides guided tutorials within VS Code to help you get started. The tutorials provide step-by-step instructions on how to develop and test your smart contract project, as well has how to deploy the smart contract to a network on IBM Cloud. You also can find sample smart contracts that are available for you to download.

To navigate to the tutorials from within VS Code, open the extensions tab and click the IBM Blockchain Platform extension under Enabled. Then, click the IBM Blockchain Platform icon at the upper right corner to view the extension homepage. On the homepage, you can find a link to the tutorials gallery and the sample smart contracts.

IBM Blockchain icon
Figure 3. Click on the IBM Blockchain icon in the upper right corner to navigate to the tutorials and sample code

Step two: Create a smart contract project

You can use the extension to create a new smart contract project in Visual Studio Code. The extension creates a basic smart contract that manages an example asset in the language of your choice. You can use the structure of the example as a starting point for developing your own business logic. The extension provides all the dependencies that are required to deploy your smart contract to an instance of Hyperledger Fabric.

  1. Click the IBM Blockchain icon to open the IBM Blockchain tab. Click the overflow menu in the smart contracts pane and click Create New Project.
  2. Select the smart contract type to generate. The Default Contract example is recommended for first-time users and demonstrates how to perform create, read, update and delete operations to the public ledger that's shared by all network members. The Private Data Contract example demonstrates how to perform create, read, update, delete and verify operations to a collection, that is private to a single network member.
  3. Select the language that you want to create a smart contract in. The current options are JavaScript, TypeScript, Go, and Java. Note: You can use the VS Code extension to create and test Java smart contracts locally. If you are deploying the smart contracts to a production network, JavaScript and TypeScript smart contracts require more resources than contracts written in Go.
  4. If you selected JavaScript, TypeScript, or Java, select an asset to be managed by the example contract. For example, bond.
  5. Create a folder with the name of your project and open it.
  6. Select how to open your new project. The project folder should now open.

When the project opens, you can find the new smart contract in the explorer window in the left pane. The structure of the project depends on the language that you selected. However, each smart contract contains the same elements:

Step three: Package a smart contract

You need to package a smart contract in .cds format before you can install it on your IBM Blockchain Platform network or the preconfigured Hyperledger Fabric network. Complete the following steps to package your smart contract:

  1. Open your smart contract project in VS Code by clicking File and then click Open .... You can also click Open Workspace if you saved your project as a workspace. Ensure that you have the smart contract project open in the file viewer.
  2. Click the IBM Blockchain icon to open the IBM Blockchain tab.
  3. In the Smart Contracts pane, click the overflow menu and select Package Open Project. You are asked for the name of the package and the version.
    • If you have one smart contract project, it is packaged automatically and be displayed in the Smart Contracts pane.
    • If you have multiple smart contract folders open, you are asked which one to package.
    • If you have no smart contract folders open, you get an error message.

If you want to control which files in the project are packaged, you can create a .fabricignore file in the top-level directory of your smart contract project. The file and pattern format for a .fabricignore file is the same as a .gitignore file, for example:

/.classpath
/.git/
/.gradle/
/.project
/.settings/
/bin/
/build/

Exporting, importing, and deleting a smart contract package

After you package a smart contract project, you can export it from VS Code:

  1. In the IBM Blockchain Platform extension panel, right-click the smart contract package and select Export Package.
  2. Choose the directory to save your smart contract package file and click Export.

You can also import an existing smart contract package into the IBM Blockchain Platform pane:

  1. In the Smart Contracts pane, click the overflow menu and select Import a Package.
  2. Browse to the smart contract package that you want to import, and click Import.

You can also click Delete Package to remove the smart contract package from the list of packages.

Step four: Deploy a smart contract to a preconfigured Hyperledger Fabric network

You can use the VS Code to deploy your smart contract to a preconfigured Hyperledger Fabric network that the extension creates on your local machine. You can then install, instantiate, and test your smart contract before you deploy it to a live network.

Deploying a preconfigured Hyperledger Fabric network

Use the following steps to deploy the preconfigured network:

  1. Ensure that Docker is running on your machine.
  2. Open the IBM Blockchain Platform tab in VS Code.
  3. In the Fabric Environments pane, click 1 Org Local Fabric. If Docker is running, the local Hyperledger Fabric instance should be downloaded and started.
  4. Click 1 Org Local Fabric - Org1 in the Fabric Gateways pane to connect to the local network. Select the org1Admin identity to connect with. You can create a new identity by right-clicking the certificate authority node in the Fabric Environments pane. This new identity can then be added to a wallet and be associated with 1 Org Local Fabric connection.

The VS Code extension creates a basic Fabric network that includes one orderer, one peer, and one certificate authority. The peer is joined to a channel named mychannel. You can find the list of nodes, organizations, and channels that belong to the network in the Fabric Environments pane. Above these nodes, you can find the list of smart contracts that are installed on your peers and instantiated on your channels.

Use the following steps to create a new one organization or two organization network:

  1. Ensure that Docker is running on your machine.
  2. Hover your mouse over the Fabric Environments pane and click +, Add Environment.
  3. Select Create new from template.
  4. Select 1 Org template (1 CA, 1 peer, 1 channel). Alternatively, if you want a larger network or have generated a Private Data Contract then select 2 Org template (2 CAs, 2 peers, 1 channel).

This will then take a few minutes to create a local Fabric network including the environment, gateways and wallets.

Stopping, restarting, tearing down and deleting a preconfigured network

You can stop or restart the preconfigured network while it is running:

  1. In the Fabric Environments pane, click the overflow menu.
  2. Select Restart, Stop, Teardown to stop, restart or teardown the container.

Selecting Teardown will completely remove the local Fabric network. Note: This removal results in the loss of the ledger and world state data.

Selecting Delete will perform a Teardown as well as remove the network from the Fabric Environments pane.

Deploying your smart contract to the preconfigured network

You can deploy any packages in the Smart Contracts pane to a running preconfigured network.

First, you need to install the smart contract on a peer:

  1. In the Fabric Environments pane, click Install Smart Contract.
  2. Select the peer(s) that you want to install the smart contract on.
  3. Select the smart contract package that you want to install, and click Install.

Next, you can instantiate the smart contract on a channel:

  1. In the Fabric Environments pane, click Instantiate Smart Contract.
  2. Select the installed smart contract to instantiate.
  3. (Optional) Enter the name of the instantiate function in your smart contract. If you used the default smart contract template, no instantiate function is used.
  4. (Optional) Enter any arguments that your instantiate function requires.
  5. (Optional) Browse to your collection configuration file if your smart contract uses private data, such as the Private Data Contract example.
  6. (Optional) Select Default or alternatively, Custom to browse for a custom smart contract endorsement policy.

If you changed your smart contract code and then repackaged it, you can upgrade the instantiated smart contract to deploy a newer version to the network:

  1. Check that you are connected to the network in the Fabric Environments pane.
  2. Ensure that the smart contract that you want to upgrade is instantiated.
  3. Install the new version of the smart contract to a peer on the same network.
  4. Right-click the instantiated smart contract, and select Upgrade Smart Contract.
  5. (Optional) Run a transaction after the new smart contract is instantiated.

Interacting with your smart contract

After a smart contract is installed and instantiated, you can submit transactions to the functions inside your smart contract by using the Fabric Gateways pane:

  1. Ensure that your smart contract is installed and instantiated, and that you are connected to the network.
  2. In the Fabric Gateways pane, expand the Channels dropdown. Click the channel that the smart contract is instantiated on.
  3. Expand the smart contract that you want to interact with. You can find the list of transactions that are listed beneath your smart contract.
  4. Right-click the transaction to submit, and select Submit Transaction. For example, if you created and packaged the example bonds smart contract, click createBond.
  5. Enter any arguments that the transaction requires, and press Enter. For example, enter ["bond01","100"] to create your first bond.
  6. (Optional) Enter any arguments that will be submitted as transient data. Transient data is not stored on the channel ledger in order to keep the data private.

Connecting your applications to the preconfigured network

You can test your client applications by connecting them to the preconfigured network and submitting transactions to your smart contract.

First, you need to export your connection profile:

  1. Ensure that the network is running in the Fabric Environments pane.
  2. Right-click on the gateway in the Fabric Gateways panel and select Export Connection Profile.

You can then use the Fabric SDKs and the connection profile to enroll your admin identity by using the username admin and the password adminpw. You can then use this identity to invoke your smart contract or register and enroll additional users.

Step five: Debug a smart contract

You can use the Debug view to iteratively develop and debug your smart contracts locally, without having to repackage and upgrade the smart contract after every change. Debugging a smart contract allows you to run through the smart contract transactions with breakpoints and output, ensuring the transactions work as intended.

You need to install some prerequisites depending on which language you are using:

Use the following steps to debug your smart contract:

  1. Ensure that you are connected to the 1 Org Local Fabric environment, or another local network create from a template.
  2. Open your smart contract project in your workspace.
  3. Open the Debug view in VS Code from the left navigation bar.
  4. Select Debug Smart Contract configuration from the drop-down list in the upper left.
  5. Clicking the play button. The extension will automatically package, install, and instantiate or upgrade the smart contract on the local network.

    If you want to debug the instantiate function in your smart contract, edit the launch configuration by using the example below.

        "env": {
        "CORE_CHAINCODE_ID_NAME": <name>:<version>
        }
    

    name is the name of your smart contract. version needs to be a different value to the previous version used. Alternatively if you are using JavaScript or TypeScript, then you can update the version in the package.json file.

  6. Add breakpoints to the smart contract by clicking the relevant line numbers in your smart contract files.

  7. On the debug toolbar, click the Blockchain button to instantiate the smart contract.
  8. On the debug toolbar, click the Blockchain button to submit or evaluate transactions. You also can right-click on transactions in the Fabric Gateways panel to submit or evaluate them. Execution will be paused on any breakpoints you define.

To modify your smart contract while debugging, click the restart button after you make changes to your smart contract. Restarting debugging means that you don't need to instantiate the contract again.

Step six: Test an instantiated smart contract

You can generate tests for smart contracts that are instantiated on the networks that you connect to. The tests can be generated as either JavaScript or TypeScript for Node projects, or Java for Java projects. Generated tests can then be run or debugged.

  1. Ensure that the smart contract is instantiated.
  2. In the Fabric Gateways pane, right-click the smart contract under the list of channels to generate tests for.
  3. Select Generate Smart Contract Tests.
  4. Select the language for the test file, either JavaScript, TypeScript or Java, depending on the smart contract language. The IBM Blockchain Platform extension installs the required dependencies and builds the test file.

After the test file is built, the tests can be run by clicking the Run Tests button in the file.

Step seven: Connect to your IBM Blockchain Platform network

You can also use the extension to interact with your network on the IBM Blockchain Platform.

Invoke a smart contract that has been instantiated on your channels

You can download your connection profile from the IBM Blockchain Platform console to build a gateway in the Fabric Gateways pane. You can then use the gateway to invoke the smart contracts that were installed and instantiated on your network.

Open the IBM Blockchain Platform console that is associated with your instance of the IBM Blockchain Platform. Navigate to the Organizations tab and click the Organization MSP tile for the organization that your client application will interact with. Click Create connection profile to open a side panel that allows you to build and download your connection profile to your local file system. Then, create an application identity by using your CA and save the enrollID and secret. Follow the steps below to connect to the IBM Blockchain Platform from VS Code.

  1. Open the IBM Blockchain Platform tab.
  2. Hover your mouse over the Fabric Gateways pane and click +.
  3. Choose Create a gateway from a connection profile.
  4. Enter a name for the connection.
  5. Enter the fully qualified file path of your connection profile. Your connection should now appear in the connections list underneath 1 Org Local Fabric.
  6. Hover your mouse over the Fabric Wallets pane and click +.
  7. Choose Create a new wallet and add an identity from the options. Provide a name for your wallet and your identity.
  8. Enter the MSP ID of your organization.
  9. Select the Select a gateway and provide an enrollment ID and secret option and choose the gateway that you created above.
  10. Enter the enrollID and secret of the application identity that you created with the console. A new identity is created in the Fabric Wallets pane.
  11. You can now connect to your instance of your IBM Blockchain Platform network. Click the connection name and select the name of the wallet that you created. You can also associate the wallet that you created with the gateway by right-clicking the gateway and selecting Associate A Wallet. This allows the connection to use the same wallet each time when it connects.

After you connect to the IBM Blockchain Platform from VS Code, you can see the list of channels joined by your organization peers under the gateway. Under each channel, you can see the list of smart contracts that are instantiated on each channel and the transactions within each smart contract. You can submit transactions to your network by right-clicking a function and selecting Submit Transaction and passing the required arguments. You can also generate a test file for the smart contracts that are instantiated on your channels.

Install and instantiate a smart contract from VS Code

You can also import the IBM Blockchain Platform network into the Fabric Environments pane of the extension. You can then use the extension to install and instantiate smart contracts on your network.

You can export nodes from your console and then import them from another console. You can use the same process to export nodes from your console and then import them into the Fabric Environments pane. The easiest way is to export all of the nodes of your console in bulk.

  1. Navigate to the Settings tab in the left navigation. You can see a section that is called Bulk data management with two buttons below it. The Export button opens a panel on the right.
  2. Keep the boxes that represent peers, CAs, and ordering services checked. Check the box to export your identities. You can leave the box that represents MSPs unchecked.
  3. Click Export to download the nodes and identities to your local file system in .zip file. Extract the file when the download is complete.

You can then import the nodes of your network into the extension.

  1. Hover your mouse over the Fabric Environments pane and click +, Add Environment.
  2. Select Add any other Fabric network.
  3. Enter a name for your network.
  4. Browse to the nodes that you exported from your console and select a node to import. After you have imported a node, click Add more (JSON) node definitions to import another node.
  5. When you have imported the CAs and peers that belong to your organization, along with the ordering nodes of your channels, click Done adding nodes.

You also need to import your admin identities into the wallet pane and associate them with your nodes. You need to associate an admin identity with your peers, CA, and an ordering node before you can connect with your network.

  1. Click on the environment that you created in the Fabric Environments pane.
  2. You can see an Alert sign next to the peer and ordering node. Click on the alert to associate an admin identity with the node.
  3. Select Add a new wallet.
  4. Select Create a new wallet.
  5. Enter a name for your wallet to identify the orderer or peer admin of your network.
  6. Select Add a new identity.
  7. Enter name for your peer or orderer admin identity.
  8. Select Provide a JSON identity file from the IBM Blockchain Platform and then browse to the admin identity that you exported from your console. If the identity is the administrator of multiple nodes in your network, you can associate the identity with multiple nodes.

When you have associated an admin identity with your peers, CA, and an ordering node, you can connect to your network and use the extension to install and instantiate smart contracts.

Adding wallets and users

Use the steps below to create a new wallet by using a certificate and private key:

  1. Hover your mouse over the Fabric Wallets pane and click +.
  2. Choose to Create a new wallet and add an identity from the options. Provide a name for your wallet and your identity.
  3. Enter the MSP ID of your organization.
  4. Choose to add a certificate and private key.
  5. If you use a certificate and private key, browse to the certificate and private key.

You can also add new users to the wallets that have already been created:

  1. In the Fabric Wallets pane, right-click a wallet and select Add Identity.
  2. Provide a name for the identity and an MSP ID.
  3. You can upload a JSON file, provide a certificate and private key, or provide an enrollment ID and secret.
    • If you are connecting to a network on the IBM Blockchain Platform, you can download an identity from your IBM Blockchain console, either by exporting an identity from your wallet or by enrolling and then exporting an identity using your Certificate Authority. You can then upload the JSON file directly to VS Code.
    • If you use a certificate and private key, browse to the certificate and private key.
    • If you use an enrollment ID and secret, choose the gateway to enroll with and enter the enrollment ID and secret.