Skip to content

Commit

Permalink
Implemented Lockup Linear MVP along with scripts and docs (#17)
Browse files Browse the repository at this point in the history
* Implemented create_with_range function

* Minor change

* feat : update test for create_with_range

* feat : Updated snforge version in yaml

* feat : Added path manually in the test.yaml

* feat : Added lockup_linear functionalities (85%)

* feat : Removed unneccessary code on get_stream fn

* feat : Adding additional read methods

* feat : Added all the view functions (100 %)

* feat : Added burn and canceling functionality

* feat : Added functionality for renounce lockup and setting nft decriptor

* feat : Added withdraw functionalities with max_and_transfer, multiple and max

* feat : Added comptroller and admin functionality

* feat : Added functionality to claim protocol revenue

* feat : Minor changes implement during code run through

* feat : Made few more changes upon code review

* feat : Under testing

* feat : Adding test cases for withdrawal

* feat : Completed tests, with coverage  about 80%

* feat : Added test cases for all the functionality

* feat : Minor change

* feat : Implemented Camel and Snake case entrypoints (ERC721)

* feat : Directory restructuring

* feat : Added example using starknetjs

* feat : Code cleanup

* feat : Code refactor

* feat : Updated documentation

* feat : Updated scripts with CLI like interaction

* feat : Added readme

* Update README.md

* Update prerequisites.md

* Update SUMMARY.md

* Update README.md

* feat : Updated get_stream

* feat : Added few more getter fns and modified the LockupLinearStream struct

* feat : Code cleanup and added comments to the new functions

* feat : Updated the scripts based on the newly added functions

* feat : Added stream_id in the LockupLinearStream struct

* feat : Changed the address to the newly deployed address

* feat : Optimization
  • Loading branch information
Akashneelesh authored Jan 29, 2024
1 parent 738cd21 commit a25ec16
Show file tree
Hide file tree
Showing 31 changed files with 5,973 additions and 632 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on: [push, pull_request]

env:
STARKNET_FOUNDRY_VERSION: 0.12.0
STARKNET_FOUNDRY_VERSION: 0.12.0

jobs:
check:
Expand All @@ -16,9 +17,8 @@ jobs:
- name: Install starknet foundry
run: |
curl -L https://raw.githubusercontent.com/foundry-rs/starknet-foundry/master/scripts/install.sh | sh -s -- -v ${STARKNET_FOUNDRY_VERSION}
echo "/root/.local/bin" >> $GITHUB_PATH
echo "Listing /root/.local/bin:"
ls -al /root/.local/bin
echo "/home/runner/.local/bin" >> $GITHUB_PATH
- name: Run cairo tests
run: |
export PATH="/root/.local/bin:$PATH"
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# will have compiled files and executables
debug/
target/

node_modules/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
Expand Down
6 changes: 6 additions & 0 deletions Scarb.lock
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Code generated by scarb DO NOT EDIT.
version = 1

[[package]]
name = "openzeppelin"
version = "0.8.0"
source = "git+https://github.com/OpenZeppelin/cairo-contracts.git?tag=v0.8.0#c23e8e96de60e6e3159b1ff8591a1187269c0eb7"

[[package]]
name = "snforge_std"
version = "0.1.0"
Expand All @@ -10,5 +15,6 @@ source = "git+https://github.com/foundry-rs/starknet-foundry.git?tag=v0.12.0#0c3
name = "tokei"
version = "0.1.0"
dependencies = [
"openzeppelin",
"snforge_std",
]
1 change: 1 addition & 0 deletions Scarb.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ sierra-replace-ids = true
[dependencies]
starknet = ">=2.3.1"
snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry.git", tag = "v0.12.0" }
openzeppelin = { git = "https://github.com/OpenZeppelin/cairo-contracts.git", tag = "v0.8.0" }


[tool.snforge]
Expand Down
40 changes: 40 additions & 0 deletions book/src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,43 @@ Tokei is a token streaming protocol, inspired by Sablier, for Starknet.
Tokei means "clock" in Japanese.

![Tokei](./assets/tokei-hello.gif)

# The Advent of Tokei: A New Era in Token Streaming

Token streaming, at its core, is the continuous transfer of assets over time. Tokei takes this concept further, offering unmatched flexibility and customizability within the Starknet ecosystem. This enables users to create bespoke streams tailored to a wide range of financial scenarios.

## Distinctive Features of Tokei

- **Linear Lockup Streams:** Tokei’s hallmark feature, these streams are crafted for a gradual and controlled fund release, perfectly suited for structured payment plans and corporate vesting schedules.
- **Customization at Its Core:** Users have the liberty to adjust parameters like start and end times, cliff durations, and can opt for stream cancelability and transferability, making Tokei versatile for various streaming needs.
- **Integration with ERC Standards:** Supporting ERC-20 tokens for streaming transactions and using ERC-721 (NFTs) to denote stream ownership, Tokei broadens its reach across different asset classes.
- **Transparent Fee Structure:** The protocol maintains clarity and fairness in its fee mechanism, outlining specific details for protocol fees and brokerage commissions.
- **Administrative Oversight:** Tokei goes beyond basic functions, offering advanced features for administrative control, such as fee settings, revenue claims, and NFT descriptor management.

## A Closer Look at Tokei’s Mechanics on Starknet

Tokei’s infrastructure skillfully manages the lifecycle of token streams, from creation to conclusion, ensuring a seamless experience.

### Stream Creation

Users can initiate streams, defining specific durations, total amounts, types of assets, and other custom conditions.

### Stream Management and Oversight

The protocol offers a comprehensive suite of functions for detailed stream analysis, including asset specifics, key milestones, deposited sums, and current status.

### Stream Conclusion

Streams can be concluded as per predefined conditions, with an efficient reallocation of funds based on the amount streamed and the remaining balance.

### Withdrawals and Ownership Transfers

Tokei allows for flexible withdrawals from streams and ownership transfers, with NFTs playing a pivotal role in facilitating these transactions.

## Practical Applications and Implications

Tokei opens up a world of possibilities within DeFi:

- **Employee Vesting:** Enterprises can use Tokei for systematic token distribution to employees, ensuring transparency and fairness in vesting processes.
- **Subscription Services:** The protocol can serve as a novel payment method for subscription services, streamlining transactions.
- **DAO Operations:** DAOs can leverage Tokei for managing ongoing contributions and distributions, thereby bolstering community engagement and financial stewardship.
2 changes: 2 additions & 0 deletions book/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@
- [Prerequisites](getting-started/prerequisites.md)
- [Build the contracts](getting-started/build.md)
- [Test the contracts](getting-started/test.md)
- [Interact with contract as a User](getting-started/user.md)
- [Interact with contract as an Admin](getting-started/admin.md)
152 changes: 150 additions & 2 deletions book/src/getting-started/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,151 @@
# Getting Started
# Getting Started with Tokei Lockup Linear Contract
Welcome to the Tokei Lockup Linear Contract on StarkNet. This guide will provide you with all the necessary information to get started with building, testing, and interacting with the contract, as well as administering it effectively.

In this section, we will go through the steps to build and test the smart contracts.
## 📝Table of Contents
- [About Tokei](#about-tokei)
- [Prerequisites](#prerequisites)
- [Building the Contracts](#building-the-contracts)
- [Testing the Contracts](#testing-the-contracts)
- [User Interaction CLI Tool](#user-interaction-cli-tool)
- [Admin Interaction Script](#admin-interaction-script)

## About Tokei
In the digital age where blockchain technology is reshaping financial landscapes, the Tokei protocol emerges as a cutting-edge solution for token streaming. Inspired by Sablier's groundbreaking work, Tokei harnesses the power of Starknet's Layer 2 capabilities to offer a novel and secure approach to token allocation and distribution, setting a new paradigm in decentralized finance (DeFi).

## **The Advent of Tokei: A New Era in Token Streaming**

At its essence, token streaming facilitates the continuous transfer of assets over time. Tokei elevates this concept by providing enhanced flexibility and customizability on Starknet, enabling users to create tailored streams that fit a plethora of financial scenarios.

### **Distinctive Features of Tokei**

- **Linear Lockup Streams**: Tokei's lockup linear streams are designed for a gradual and controlled release of funds, ideal for structured payment plans and corporate vesting schedules.
- **Customization at Its Core**: With adjustable parameters like start and end times, cliff durations, and options for cancelability and transferability, Tokei caters to diverse streaming needs.
- **Integration with ERC Standards**: Tokei supports ERC-20 tokens for streaming transactions and leverages ERC-721 (NFTs) to represent stream ownership, expanding its utility across asset classes.
- **Transparent Fee Structure**: The platform ensures fair dealings with a clear-cut mechanism for protocol fees and brokerage commissions.
- **Administrative Oversight**: Advanced features allow for administrative interventions, including setting fees, claiming revenues, and managing NFT descriptors.

## **A Closer Look at Tokei's Mechanics on Starknet**

Tokei's smart contract infrastructure orchestrates the entire lifecycle of token streams, from their inception to conclusion.

### **Stream Creation**

Participants can initiate streams with specific durations or date ranges, defining the total amount and the type of asset, as well as other bespoke conditions.

### **Stream Management and Oversight**

The protocol provides a suite of functions for obtaining comprehensive details about each stream, such as asset details, key timepoints, deposited sums, and the stream's current state.

### **Stream Conclusion**

Streams can be terminated based on predefined conditions, with the protocol adeptly reallocating funds relative to the amount streamed and the remaining balance.

### **Withdrawals and Ownership Transfers**

Users can withdraw from streams or transfer ownership, facilitated by NFT representations, further emphasizing Tokei's commitment to flexibility and security.

## **Practical Applications and Implications**

Tokei's protocol unlocks a myriad of possibilities within the DeFi ecosystem:

- **Employee Vesting**: For example, enterprises can implement Tokei to distribute tokens to employees systematically, thereby ensuring a transparent vesting journey.
- **Subscription Services**: Businesses can adopt token streaming as a payment method for subscription services, providing a seamless transaction flow.
- **DAO Operations**: DAOs can employ Tokei to regulate ongoing contributions and distributions, enhancing community engagement and financial management.

## **Visualizing Token Streaming with Tokei**

Let's visualize the process with an example:

- **Scenario**: Evelyn wishes to stream 10,000 XYZ tokens to Jordan over three months.
- **Execution**: She locks the XYZ tokens into Tokei's smart contract at the start of April, with the stream set to end in July.
- **Token Accrual**: As the days of April unfold, Jordan's balance begins to grow in real-time.
- **Withdrawal Option**: By the 10th of April, Jordan has access to a portion of the tokens and can choose to withdraw at any time.

*The graph here depicts a consistent token stream without a cliff.*

<img width="528" alt="Screenshot 2024-01-25 at 11 35 54 PM" src="https://github.com/Akashneelesh/tokei/assets/66639153/68abfa36-3117-452c-87b7-d0e1a73e6d95">


Should Evelyn choose to retract her tokens, she has the autonomy to cancel the stream and retrieve the unstreamed tokens.

### **Introducing Cliffs for Enhanced Control**

Tokei introduces the concept of cliffs to add a strategic pause in the token release schedule:

- **Vesting with Cliffs**: Consider a business that sets a 6-month cliff for an employee's token vesting, followed by a 2-year linear stream. If the employee exits the company prematurely, the business can cancel the stream and secure the assets not yet streamed.

*This graph showcases a Lockup Linear stream with a cliff. The horizontal plateau represents the cliff duration, after which the linear increase in streamed tokens resumes.*

<img width="522" alt="Screenshot 2024-01-25 at 11 36 06 PM" src="https://github.com/Akashneelesh/tokei/assets/66639153/b787c0f0-38a6-42e3-af83-d9233d81bd4e">


## 📖Prerequisites
Before you begin, make sure you have the following prerequisites installed:

- Starknet Foundry
- Scarb
- Starknet.js
- Node.js (for User and Admin scripts)
- TypeScript



More details: [Starknet Foundry](https://foundry-rs.github.io/starknet-foundry/)

## 🏗️ Building the Contracts
To build the smart contracts, open a terminal and execute:

```bash
scarb build
```
This command will compile the smart contracts and output them to the target directory. For a detailed structure of the output, see [build.md]((https://github.com/Akashneelesh/tokei/blob/main/book/src/getting-started/build.md)).

## 🔨Testing the Contracts
Run the following command to test the contracts:
```bash
snforge test
```
This executes tests located in the tests directory. Sample output:

```
Collected 38 test(s) from tokei package
Running 38 test(s) from src/
[PASS] tokei::tests::... (detailed test results)
```

For more detailed view about the test cases see [test.md](https://github.com/Akashneelesh/tokei/blob/main/book/src/getting-started/test.md).

## ⚙ User Interaction CLI Tool
The User Interaction CLI tool is designed for easy interaction with the streaming contract. It supports various functionalities such as creating streams, withdrawing funds, and querying stream details. To use this tool, you need to install certain dependencies and follow the steps outlined in [user.md](https://github.com/Akashneelesh/tokei/blob/main/book/src/getting-started/user.md).

### Key functionalities include:

- Stream creation and management
- Asset management
- Fee and NFT integration

For detailed instructions on installation, usage, and examples, please refer to [user.md](https://github.com/Akashneelesh/tokei/blob/main/book/src/getting-started/user.md).

## 👮‍♂️ Admin Interaction Script
The Admin Interaction Script facilitates the management of the Tokei Lockup Linear Contract. It includes features for setting and retrieving protocol fees, claiming protocol revenues, and viewing administrative details.

### Key aspects include:
- Stream creation and management
- Fee handling
- NFT Integration
- Core functionalities and key structures
For complete guidelines on installation, usage, and available functions, see [admin.md](https://github.com/Akashneelesh/tokei/blob/main/book/src/getting-started/admin.md).

## 📚 Resources

Here are some resources to help you get started:

- [Cairo Book](https://book.cairo-lang.org/)
- [Starknet Book](https://book.starknet.io/)
- [Starknet Foundry Book](https://foundry-rs.github.io/starknet-foundry/)
- [Starknet By Example](https://starknet-by-example.voyager.online/)
- [Starkli Book](https://book.starkli.rs/)

## 📖 License

This project is licensed under the **MIT license**. See [LICENSE](LICENSE) for more information.
128 changes: 128 additions & 0 deletions book/src/getting-started/admin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# StarkNet Admin Interaction Script

## 🔍 Overview

The Tokei Lockup Linear Contract on StarkNet facilitates the creation and management of time-bound asset streams. This guide delves into the functionalities, fee structures, and key contract components like `Durations`, `Range`, `Broker`, and `LockupLinearStream`.
The Tokei Lockup Linear Contract offers a comprehensive solution for asset distribution on StarkNet. Its sophisticated structures enable precise control over asset streaming, making it an essential tool for DeFi applications. A deep understanding of its fee calculations and time-bound mechanisms is key for effective implementation.

## 💪 Core Functionalities

### Stream Creation and Management

- Create asset streams with specific timings using the `Range` structure.
- Support for cancelable and transferable streams.
- Functions for withdrawing assets according to the stream schedule.

### Fee Handling

- Management of protocol and broker fees based on the total stream amount.
- Limitations to prevent excessive fee charges.

### NFT Integration

- Representation of each asset stream as an NFT for ease of tracking and transferability.

## 🔑 Key Structures and Functions

### Fee Calculation (`check_and_calculate_fees`)

- **Inputs**: Total stream amount, protocol fee percentage, broker fee percentage, max fee limit.
- **Outputs**: Calculated deposit, protocol fee, and broker fee in `CreateAmounts` struct.
- **Process**:
- Validation of protocol and broker fees against the maximum fee limit.
- Calculation of absolute fee amounts.
- Verification that total amount covers both fees, with remainder as the deposit amount.

### PercentageMath Trait

- Utilized for calculating fee percentages as a proportion of the total amount.

### Scaled Division (`scaled_down_div`)

- Function for dividing with scaling, used in time-related calculations.

### Range and Durations

- **Range**: Defines timestamps for the start, cliff, and end of an asset stream.
- **Durations**: Represents cliff and total duration in time units.

### LockupLinearStream Structure

- Represents an asset stream, including financial tracking through `LockupAmounts`.
- **LockupAmounts**: Encapsulates deposited, withdrawn, and refunded amounts.

### Validation Checks (`check_create_with_range`)

- Ensures timing integrity and deposit amount of the stream.
- Checks for valid timing sequence and that current time precedes the end time.

## Features
- Setting and retrieving protocol fees
- Claiming protocol revenues
- Viewing administrative details
- Dynamic interaction with smart contracts

## 🏗️ Prerequisites
Before running this script, ensure you have the following installed:
- Node.js and npm
- StarkNet libraries and ethers.js
- TypeScript and ts-node

## ⚙️ Installation
To set up the script on your local machine, follow these steps:
1. Clone the GitHub repository:
2. Navigate to the repository directory and install the required dependencies:

```bash
npm install or yarn
```

## 🛠️ Build the contracts
```bash
scarb build
```

## 🤺 Usage
To execute the script, run the following command in the root directory of the project:
```bash
npx ts-node src/scripts/admin_interaction.ts
```

Upon running the command, the script will initiate a CLI, prompting you to select from a range of functions for execution. Follow the on-screen instructions to interact with the smart contracts.

## Available Functions
The script offers various functionalities, categorized into "view" and "write" operations:

### View Functions
- `get_admin`
- `get_flash_fee`
- `get_protocol_fee`
- `get_protocol_revenues`

### Write Functions
- `set_flash_fee`
- `set_protocol_fee`
- `claim_protocol_revenues`

## 💰Setting Protocol Fees

As an administrator, you can adjust the protocol fees charged by Tokei. Here's how to set the protocol fee using the **`set_protocol_fee`**
- Enter the function name in this case : set_protocol_fee
- You will be prompted with the protocol fee to be set, enter the amount.
- And that's all you would have successfully set the protocol fee.

Here's an example of how you can set the protocol fee :
<img width="1373" alt="Screenshot 2024-01-25 at 9 56 17 PM" src="https://github.com/Akashneelesh/tokei/assets/66639153/43de5d3a-29cb-4297-b45b-84b546262f2a">

## Getting the Protocol Fees
Here's an example of how you can retrieve the protocol fee
function:<img width="1374" alt="Screenshot 2024-01-25 at 9 55 08 PM" src="https://github.com/Akashneelesh/tokei/assets/66639153/13a404c4-c700-4e47-944b-d8a63e0488ab">
For each function, you will be prompted to input the necessary parameters before execution.

## **Finalizing Your Admin Tasks**

After you've set fees or claimed revenues, verify the transactions have processed successfully by checking the Starknet block explorer with the transaction hashes output by the script.

## **Conclusion**

Administering the Tokei protocol requires a careful approach to manage fees and revenues effectively. By following the steps outlined in this guide, you can confidently execute administrative tasks, ensuring Tokei continues to operate smoothly on the Starknet platform.
Loading

0 comments on commit a25ec16

Please sign in to comment.