# Writing a smart contract in TypeScript (TS)

### Sample contract functionality

The sample contract serves as a demonstration of general QVM logic.

It is capable of:

* registering users into the database
* storing the last registered user's name in the database
* echoing the previous user's name to STDOUT
* incrementing the total registered user count
* storing above counter in the database

### Sample code

```c
function contract(args: string[]) {

  // THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
  if (args && args.length === 2 && args[0] === "register") {

    // GET THE CURRENT USER'S NAME OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
    const previous_name: string = process.env.DB_USER_CURRENT || "unknown";

    // GET THE TOTAL USER COUNT
    const total_user_count: number = parseInt(process.env.DB_TOTALUSERS || "0");

    // WRITE PREVIOUS USER NAME TO STDOUT
    process.stdout.write(`OUT=prevname: ${previous_name}\n`);

    // UPDATE CURRENT USER NAME BY WRITING IT TO DB
    process.stdout.write(`DBW=USER_CURRENT=${args[1]}\n`);

    // STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
    process.stdout.write(`DBW=USER_${total_user_count}=${args[1]}\n`);

    // INCREMENT THE TOTAL USER COUNT
    process.stdout.write(`DBW=TOTALUSERS=${(total_user_count + 1)}\n`);
    process.exit(0);
  }

  if (args.length >= 1) {
    process.stderr.write(`Wrong CMD: ${args[0]}\n`);
    process.exit(1);
  }

  process.stderr.write("Wrong args!\n");
  process.exit(1);
}

contract(process.argv.slice(2));
```

### Save the contract

Open a text editor and save above sample contract as `main.ts` file.

{% content-ref url="/pages/GEqhn5JblxJW5MXZuBwt" %}
[Compiling a smart contract in TypeScript (TS)](/developers/qvm-multi-language-smart-contracts/docs-for-supported-languages/typescript-ts-smart-contract/compiling-a-smart-contract-in-typescript-ts.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learn.qanplatform.com/developers/qvm-multi-language-smart-contracts/docs-for-supported-languages/typescript-ts-smart-contract/writing-a-smart-contract-in-typescript-ts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
