bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 66쪽
o it:
* **Constructor removal**\
Having a constructor in an implementation contract doesn't make much sense as the actual storage used will be the proxy's one.
* **Immutable modifier**\
Since the constructor was removed, the next step needed was to change the `decimals` variable from an `immutable` to a editable storage variable, to ensure that the proxied contracts could correctly reference it.
* **Making it abstract**\
The resulting contract was marked as abstract, to make signify that it's incomplete and inheriting contracts need to implement functions to correctly return `name`, `symbol` and `decimal`.
The gist of the difference between the two version of the token can be seen [here](https://www.diffchecker.com/tbN1DhN8/)
# Modules
### Exposing Mints and Burns
The `mint` and `burn` functions of the SYRUP contract need to be exposed only to authorized actors. While the ERC20 contract does not distinguish between different types of actors, SYRUP prefers using minting modules to enforce strict rules. The mint function in the base token will be kept simple and only include authorization checks. The control over the total supply or availability of tokens will reside with the authorized actors.
### Modules
Modules are smart contracts with pre-defined rules that can mint or burn MPL tokens. Authorized modules have a significant impact on the token and the protocol and should aim for simplicity to avoid unintended consequences. The onboarding and offboarding of modules will be performed off-chain. The SYRUP contract will store a single authorized address that can add or remove modules. This entity, such as the `GovernorTimelock` (managed by a multisig) or another account, is assumed to act according to off-chain governance decisions. The token itself will not impose any restrictions or checks on the actions of allowing modules.
To activate the module, the following actions needed to be taken:
```
1. An off-chain proposal for adding the module was made.
2. If the proposal was passed, the allowed entity scheduled an execution in the Globals contract.
3. After the time lock period passed, the module could be added as an authorized minter.
4. According the the specific module rules, tokens can be minted or burned.
```
# Time Locks
To ensure that all stakeholders can take action in case of unwanted events, administrative functions should be time-locked before execution. The following functions will have a time lock:
* Add Module
* Remove Module
* Upgrade
Note that since the modules themselves call the mint function, it does not need to be time-locked. The current protocol already has a similar time-locking mechanism in place, which can be leveraged for SYRUP.
# Recapitalization Module
The RecapitalizationModule contract provides functionalities related to Recapitalization in a protocol. It allows for the claiming of tokens based on predefined issuance windows and manages the scheduling of these windows.
Here is a summary of what the RecapitalizationModule contract does:
1. Claiming Tokens: The contract allows designated Recapitalization claimers to claim tokens based on predefined issuance windows. Claimers can call the `claim` function to claim tokens. The claimable amount is calculated based on the issuance rate specified for each window and the `claim` function is restricted to callers with the `RECAPITALIZATION_CLAIMER` tag in Global's `isInstance` mapping.
2. Viewing Claimable Tokens: The contract provides a function `claimable` that allows anyone to view the amount of tokens that can be claimed up to a specified timestamp. This provides transparency and visibility into the claimable tokens.
3. Managing Issuance Windows: The contract supports the scheduling of issuance windows. The governor, as defined in the associated Globals contract, can schedule new issuance windows by specifying window start timestamps and corresponding issuance rates. These windows determine the issuance rates for the tokens during different periods.
4. Determining Current Issuance Rate: The contract provides a function `currentIssuanceRate` that returns the issuance rate for the current issuance window based on the current timestamp. This allows users to know the current rate at which new tokens are being issued.
## Issuance Windows
The contract maintains a list of `windows`, which each represents a specific time period during which tokens are issued at a predefined rate. There are 2 main factors that define a window: **start**: The timestamp that defines when the window becomes valid. **issuanceRate**: The amount of tokens per seconds that will be issued during that window. **nextWindowId**: This structure is implemented as a linked list, so each window saves a reference to the next window. If this value is zero, it means that it's the last schedule in the list.
Note that windows don't have a specific end time, so they'll be forever valid until a subsequent window is scheduled.
## Scheduling
It's the act of lining up issuance windows to effectively change the issuance rate of the token. It's only possible to schedule a window with a future start date, including required timelock duration.
To properly schedule a issuance window, the following steps need to be done:
1. `Governor` should call `Globals.scheduleCall(module address, function id, encoded data)`, where:
* `module address`: The deployed address of the Recapitalization module contract.
* `function id`: A bytes 32 indicating which function is being scheduled. In this case it's `"IM:SCHEDULE"`.
* `encoded data`: Which can be computed using: `abi.encodeWithSelector(RecapitalizationModule.schedule.selector, uint32[] windowStarts, uint208[]issuanceRates)`
2. After the time lock period passed, the `Governor` should call `module.schedule(uint32[] windowStarts, uin208[]issuanceRates)`.
### Scheduling Parameters
The `schedule()` function takes 2 arrays as parameter, one for the starts of each issuance window, and the other for the issuance rates, represented by the amount of tokens per second.
For example, let's use the proposed distribution for the 3 year period described in the [MIP-009](https://community.maple.finance/t/mip-009-upgrade-mpl-token-design/300)

Here's how to derive each parameter:
1. Get the timestamps of the desired periods. There's a need to schedule 4 windows so the issuance stops after the third full year. Those values are:
* **1696132800** -> October 1st 00:00 2023 EST
* **1704081600** -> January 1st 00:00 2024 EST
* **1735704000** -> January 1st 00:00 2025 EST
* **1767240000** -> January 1st 00:00 2026 EST
Thess will be be the first parameter to `schedule`.
2. Get the duration, in seconds, of each desired period. Those values are:
* **7948800** -> 92 days (October 1st 2023 - December 31st 2023)
* **31622400** -> 366 days (January 1st 2024 - December 31st 2024)
* **31536000** -> 365 days (January 1st 2025 - December 31st 2025)
* **23587200** -> 273 days (January 1st 2026 - September 30th 2026)
3. To get the proper issuance rate, just divide the desired number of tokens including decimals, taken from the MIP, by the period duration, from step 2:
* **1st Period**: `125000e18 / 7948800 = 15725644122383252`
* **2nd Period**: `566767e18 / 31622400 = 17922959674155030`
* **3rd Period**: `595641e18 / 31536000 = 18887652207001524`
* **4th Period**: `39134200e18 / 23587200 = 1659128679962013200`
* **5th Period**: 0, since the issuance stops after the third year.
The next step is to divide the amount of tokens, by the duration of the period, which would yield the following results:`[15725644122383252, 17922959674155030, 18887652207001524, 1659128679962013200, 0]`
In conclusion, to configure the mentioned issuance schedule, the function to be called is:
```
module.schedule([1696132800, 1704081600, 1735704000, 1767240000, 1790827200],[15725644122383252, 17922959674155030, 18887652207001524, 1659128679962013200, 0])
```
### Insertion Logic
The insertion logic works as follow:
```
The Recapitalization module has a defined schedule of issuance that defines how new tokens will be issued over time.
Here is an example of an issuance schedule with three windows, the first two windows have a defined start and end.
The last window has a defined start but lasts indefinitely after it starts since it is the last window in the schedule.
|--------|------|---------------->
W1 W2 W3
Each window has a separate issuance rate, which defines how many tokens per second will be issued during it's duration.
The issuance rate generally increases over time and is used to simulate the effect of compounding (for example on a yearly basis).
However the issuance rate can also be zero to indicate that no tokens should be issued.
|----|==============|________|≡≡≡≡≡≡≡≡≡≡≡≡>
W1 W2 W3 W4
New windows can be scheduled, but only from the current time, retroactive scheduling is not possible.
When new windows are scheduled after the last window in the schedule starts, they will be appended to the schedule.
|--------|----------|----------------->
W1 W2 ^ W3
|
|--------|----------|----|------------>
W1 W2 W3 W4
When new windows are scheduled before any of the existing windows in the schedule start, they will replace them instead.
|--------|----------|--------------->
W1 W2 ^ W3
|
|--------|-------|------------------>
W1 W2 W4
```
# Emergency Module
The EmergencyModule contract is designed to handle emergency situations within a protocol. It provides functionalities for burning and minting tokens under the control of the governor, as defined in the associated Globals contract.
It is not intended to be deployed, but rather just have it ready in case of any future emergency.
## Features
**Burning Tokens:** The contract allows the governor to burn a specified amount of tokens from a given address. This functionality can be used to remove tokens from circulation in emergency scenarios.
**Minting Tokens:** The governor can also mint a specified amount of tokens to the Maple Treasury address. This functionality enables the creation of new tokens in emergency situations.
Both calls can only be triggered by the Governor.
# Deployment and Migration Procedure
## Phase 1 - Deployment of contracts
The following contracts will need to be deployed, in this specific order:
| Step | Contract | Constructor Arguments |
| ---- | --------------------------------------- | ------------------------------------------------------------------------------ |
| 1 | MapleToken (Implementation) | - |
| 2 | MapleTokenInitializer | - |
| 3 | MapleTokenProxy (Non-Transparent-Proxy) | globals address, implementation address(1), initializer address(2), migrator\* |
| 4 | RecapitalizationModule | token address(3) |
| 5 | Migrator | mplv1 address, SYRUP address(3)\* |
\*There is a circular dependency between steps 3 and 5, as both depend on a contract deployed by the other. The solution to this is to rely on the deterministic addresses, which allows for computing the address that a contract will be deployed to before it actually happens. Therefore, for stage 3, using the sender key, we pre-compute the address that the Migrator will be deployed to, and pass that as a parameter.
After this step, the migrator is already able to exchange MPL V1 to SYRUP at 1:1 exchange rate.
## Phase 2: Recapitalization Module setup
To add any module to the SYRUP contract, the following transactions need to be made:
1. `Governor` should call `Globals.scheduleCall(token address, function id, encoded data)`, where:
* `token address`: The deployed address of the `MapleTokenProxy` contract.
* `function id`: A bytes 32 indicating which function is being scheduled. In this case it's `"MT:ADD_MODULE"`.
* `encoded data`: Which can be computed using: `abi.encodeWithSelector(IMapleToken.addModule.selector, module)`
2. After the time lock period passed, the `Governor` should call `Token.addModule(module)`, where module is the Recapitalization module address.
3. The module is now able to mint tokens according to its specific business rule. However, to kickstart the issuance, an issuance window needs to be scheduled. Refer to [this documentation](https://github.com/maple-labs/maple-docs/blob/master/technical-resources/syrup/technical-resources/syrup/recapitalization-module.md#scheduling) for how to do that.
4. The `Governor` needs to set an actor as `RECAPITALIZATION_CLAIMER` in Globals, using the function `setInstanceOf("RECAPITALIZATION_CLAIMER", claimer address, true)`.
## Phase 3 - Migration

The migration process leverages the migration contract, which allows for a 1:1 exchange from the old token to SYRUP. To perform the migration, the migrator token must hold 10 million units of SYRUP.
### Standalone Migrations
Other entities can migrate performing the following steps:
1. Approve the `amount` of tokens to the `migrator` contract.
2. Call the the function `migrate(amount)`
The user should now have received exactly `amount` of SYRUP tokens. This process will be available forever, meaning that, as long as someone have MPLv1 tokens, they can always receive the 1:1 of MPLv2.
# SDK
# Maple SDK Introduction: Developer Guide
## Introduction
`maple-js` is a powerful and user-friendly JavaScript SDK designed for seamless interaction with Maple Protocol's smart contracts on the Ethereum blockchain. This SDK provides developers with essential tools to easily integrate with the Maple Protocol ecosystem, streamlining the process of connecting to the blockchain, managing accounts, submitting transactions, and handling events generated by smart contracts.
By utilizing the JavaScript SDK for Maple Protocol, developers can efficiently build robust and secure dApps that unlock the full potential of Maple Protocol's smart contracts, encouraging innovation and promoting the adoption of decentralized finance solutions.
Whether you're developing backend services, frontend applications, or a combination of both, the Maple SDK offers the tools necessary for a smooth user experience.
## Exports
### Addresses
| Export | Purpose |
| ----------- | -------------------------------------------------------------------------------------------------------- |
| `addresses` | Contains the contract addresses for the Maple Protocol on different networks (mainnet & Sepolia testnet) |
### TypeChain
`maple-js` exports are provided via TypeChain - convenient and error-resistant way for developers to call smart contract functions, ensuring a smoother integration with Maple Protocol's ecosystem.
TypeChain exports are automatically generated TypeScript bindings for Ethereum smart contracts. These bindings make it easier for developers to interact with smart contracts by providing type-safe methods for contract functions. This means that developers can leverage TypeScript's type-checking and autocomplete features, reducing the likelihood of errors and improving the overall development experience.
| Export | Purpose |
| ---------------------- | --------------------------------------------------------------------------- |
| `bPool` | Manages Balancer liquidity pool functionality |
| `erc20` | Standard ERC20 token contract functionality |
| `fixedTermLoanManager` | Manages fixed-term loan creation and management functionality |
| `loanManager` | Manages loan creation and management functionality |
| `loanV5` | Implements loan v5 functionality |
| `mapleGlobalsV2` | Manages global settings and configurations for Maple Protocol (version 2) |
| `mapleGlobalsV2V2` | Manages global settings and configurations for Maple Protocol (version 2.2) |
| `mapleToken` | Implements the Maple Protocol token functionality |
| `openTermLoan` | Implements open-term loans functionality |
| `openTermLoanManager` | Manages open-term loan creation and management functionality |
| `poolManager` | Manages pool creation and management functionality |
| `poolManagerV2` | Manages pool creation and management functionality (version 2) |
| `poolV2` | Manages liquidity pools in the Maple Protocol ecosystem (version 2) |
| `withdrawalManager` | Manages withdrawal functionality in the Maple Protocol ecosystem |
| `xmpl` | Implements the XMPL token functionality |
Depending on the smart contract package structure, the SDK export might include different properties, such as `core`, `factory`, `initializer`, `deployer`, which can be accessible through the export. For example, the `openTermLoan` export includes the following properties:
```js
const openTermLoan = {
core: MapleLoan__factory,
factory: MapleLoanFactory__factory,
initializer: MapleLoanInitializer__factory,
};
```
### Types
| Export | Purpose |
| --------------------- | --------------------------------------------------------------------------------------- |
| `ContractTypes` | Enumerates different contract types in the Maple Protocol ecosystem |
| `MapleAddressMapping` | Mapping of contract addresses to their respective types in the Maple Protocol ecosystem |
# Installation
The SDK is available as a single package, installable using your preferred package manager:
```bash
npm install @maplelabs/maple-js
// or if using yarn
yarn add @maplelabs/maple-js
```
⚠️ Important Note on SDK Versioning: Regularly check for updates and new releases to access the latest features, improvements, and bug fixes. Monitor the SDK's versioning by visiting the official repository, subscribing to release notifications, or checking your package manager's update logs. This ensures optimal experience and compatibility with the Maple Protocol ecosystem.
⚠️ **Beta Disclaimer:** Please be aware that the SDK is currently in beta. While we strive to provide the best possible experience, using it is at your own risk. We appreciate your understanding and encourage you to provide feedback on any issues or suggestions for improvements.
## Developer Links
* [Maple SDK GitHub repo](https://github.com/maple-labs/maple-js)
* [Maple Smart Contracts v2 GitHub repo](https://github.com/maple-labs/maple-core-v2)
## Requirements
* [ethers v5](https://docs.ethers.org/v5/)
# Protocol Actors: Maple SDK Reference
## Protocol Actors
There are three actors in the Maple Protocol ecosystem:
* Borrowers
* Lenders
* Pool Delegates
## Borrowers
* Borrowers initiate loan requests by specifying terms and providing collateral if required.
* Borrowers draw down loans after they are approved and funded.
* Borrowers repay principal and interest through associated smart contracts.
**Code Example:** This snippet queries the [`GlobalsV2`](https://maplefinance.gitbook.io/maple/technical-resources/protocol-overview/smart-contract-architecture#maple-globals) contract to check if a given address is an authorized borrower
```js
import { providers } from 'ethers';
import { addresses, mapleGlobalsV2 } from '@maplelabs/maple-js';
const RPC_ENDPOINT = 'https://mainnet.infura.io/v3/{YOUR_KEY}';
async function main() {
const contract = mapleGlobalsV2.core.connect(
addresses['mainnet-prod'].MapleGlobalsV2,
new providers.JsonRpcProvider(RPC_ENDPOINT)
);
const isBorrower = await contract.isBorrower('YOUR_ADDRESS');
console.log({ isBorrower });
}
main();
```
## Lenders
* Lenders deposit specific assets into designated pools.
* Lenders accumulate interest on deposits as borrowers repay loans.
* Lenders withdraw assets from pools using the `WithdrawalManager` contract.
**Code Example:**
```js
import { BigNumber, providers } from 'ethers';
import { addresses, poolV2, erc20 } from '@maplelabs/maple-js';
const RPC_ENDPOINT = 'https://mainnet.infura.io/v3/{YOUR_KEY}';
const POOL_ADDRESS = '{POOL_ID}';
async function main() {
const provider = new providers.JsonRpcProvider(RPC_ENDPOINT);
const poolContract = poolV2.core.connect프로젝트로 돌아가기