├── .gitattributes ├── .solcover.js ├── test ├── shared │ ├── expect.ts │ ├── config.ts │ ├── matchers │ │ ├── index.ts │ │ ├── supportRevertCustomError.ts │ │ ├── supportMargin.ts │ │ └── supportPosition.ts │ ├── utils.ts │ ├── permit.ts │ ├── fixture.ts │ └── calibration.ts ├── liquidityManager.ts └── liquidityWrapper.ts ├── .solhint.json ├── .prettierrc.json ├── contracts ├── test │ ├── TestERC20.sol │ ├── TestERC1155Permit.sol │ └── WETH9.sol ├── primitiveChef │ ├── RewardToken.sol │ ├── IPrimitiveChef.sol │ └── PrimitiveChef.sol ├── liquidityWrapper │ ├── LiquidityWrapper.sol │ └── ILiquidityWrapper.sol └── liquidityManager │ ├── ILiquidityManager.sol │ └── LiquidityManager.sol ├── tsconfig.json ├── hardhat.config.ts ├── package.json ├── types └── index.d.ts ├── .gitignore ├── README.md └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity -------------------------------------------------------------------------------- /.solcover.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | skipFiles: ['test/'], 3 | } 4 | -------------------------------------------------------------------------------- /test/shared/expect.ts: -------------------------------------------------------------------------------- 1 | import { expect, use } from 'chai' 2 | import { solidity } from 'ethereum-waffle' 3 | 4 | use(solidity) 5 | 6 | export default expect 7 | -------------------------------------------------------------------------------- /test/shared/config.ts: -------------------------------------------------------------------------------- 1 | import { parsePercentage } from "web3-units"; 2 | 3 | import { Calibration } from "./calibration"; 4 | 5 | export const DEFAULT_CALIBRATION = new Calibration(10, 1, 1672531200, 1, 10, parsePercentage(1 - 0.0015)); 6 | -------------------------------------------------------------------------------- /.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "plugins": ["prettier"], 4 | "rules": { 5 | "mark-callable-contracts": "off", 6 | "max-line-length": ["warn", 120], 7 | "prettier/prettier": "error" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "overrides": [ 3 | { 4 | "files": "*.sol", 5 | "options": { 6 | "printWidth": 80, 7 | "tabWidth": 4, 8 | "useTabs": false, 9 | "singleQuote": false, 10 | "bracketSpacing": false, 11 | "explicitTypes": "always" 12 | } 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /contracts/test/TestERC20.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity 0.8.9; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | 6 | contract TestERC20 is ERC20("TestERC20", "TEST") { 7 | function mint(address account, uint256 amount) external { 8 | _mint(account, amount); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/shared/matchers/index.ts: -------------------------------------------------------------------------------- 1 | import supportRevertCustomError from './supportRevertCustomError' 2 | import supportMargin from './supportMargin' 3 | import supportPosition from './supportPosition' 4 | 5 | // Custom Chai matchers for Primitive v2 6 | 7 | export default function primitiveChai(chai: Chai.ChaiStatic) { 8 | supportRevertCustomError(chai.Assertion) 9 | supportMargin(chai.Assertion) 10 | supportPosition(chai.Assertion) 11 | } 12 | -------------------------------------------------------------------------------- /contracts/test/TestERC1155Permit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity 0.8.6; 3 | 4 | import "@primitivefi/rmm-manager/contracts/base/ERC1155Permit.sol"; 5 | 6 | contract TestERC1155Permit is ERC1155Permit { 7 | function mint( 8 | address account, 9 | uint256 id, 10 | uint256 amount 11 | ) external { 12 | bytes memory data; 13 | _mint(account, id, amount, data); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2018", 4 | "module": "commonjs", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "resolveJsonModule": true, 8 | "preserveSymlinks": true, 9 | "outDir": "dist", 10 | "noImplicitAny": false 11 | }, 12 | "ts-node": { 13 | "files": true 14 | }, 15 | "include": ["./test", "./src", "./scripts", "./types"], 16 | "files": ["./hardhat.config.ts"] 17 | } 18 | -------------------------------------------------------------------------------- /hardhat.config.ts: -------------------------------------------------------------------------------- 1 | import '@typechain/hardhat' 2 | import '@nomiclabs/hardhat-ethers' 3 | import '@nomiclabs/hardhat-waffle' 4 | import { HardhatUserConfig } from 'hardhat/config' 5 | 6 | const config: HardhatUserConfig = { 7 | networks: { 8 | hardhat: { 9 | blockGasLimit: 18e6, 10 | gas: 12e6, 11 | }, 12 | }, 13 | solidity: { 14 | compilers: [ 15 | { version: '0.8.6' }, 16 | { version: '0.8.9' }, 17 | ], 18 | }, 19 | } 20 | 21 | export default config 22 | -------------------------------------------------------------------------------- /test/shared/utils.ts: -------------------------------------------------------------------------------- 1 | import { 2 | utils, 3 | BigNumber, 4 | } from 'ethers' 5 | 6 | const { keccak256, solidityPack } = utils 7 | 8 | export function computePoolId( 9 | engine: string, 10 | maturity: string | number, 11 | sigma: string | BigNumber, 12 | strike: string | BigNumber, 13 | gamma: string | BigNumber 14 | ): string { 15 | return keccak256( 16 | solidityPack(['address', 'uint128', 'uint32', 'uint32', 'uint32'], [engine, strike, sigma, maturity, gamma]) 17 | ) 18 | } 19 | 20 | /** 21 | * Statically computes an Engine address. 22 | * 23 | * @remarks 24 | * Verify `bytecode` is up-to-date. 25 | * 26 | * @param factory Deployer of the Engine contract. 27 | * @param risky Risky token address. 28 | * @param stable Stable token address. 29 | * @param bytecode Bytecode of the PrimitiveEngine.sol smart contract. 30 | * 31 | * @returns engine address. 32 | * 33 | * @beta 34 | */ 35 | export function computeEngineAddress(factory: string, risky: string, stable: string, bytecode: string): string { 36 | const salt = utils.solidityKeccak256( 37 | ['bytes'], 38 | [utils.defaultAbiCoder.encode(['address', 'address'], [risky, stable])] 39 | ) 40 | return utils.getCreate2Address(factory, salt, utils.keccak256(bytecode)) 41 | } 42 | -------------------------------------------------------------------------------- /test/shared/matchers/supportRevertCustomError.ts: -------------------------------------------------------------------------------- 1 | // Chai matcher for custom revert errors 2 | 3 | export default function supportRevertCustomError(Assertion: Chai.AssertionStatic) { 4 | Assertion.addMethod('revertWithCustomError', async function (this: any, errorName: string, params?: any[]) { 5 | try { 6 | await this._obj 7 | } catch (e: any) { 8 | const msg: string = e?.message 9 | const [, revertMsg] = msg?.split("'") 10 | 11 | const [actualErrorName, actualParamsRaw] = revertMsg.split('(') 12 | const actualParams = actualParamsRaw 13 | .substring(0, actualParamsRaw.length - 1) 14 | .replace(/ /g, '') 15 | .split(',') 16 | 17 | this.assert( 18 | actualErrorName === errorName, 19 | `Expected ${actualErrorName} to be ${errorName}`, 20 | `Expected ${actualErrorName} NOT to be ${errorName}`, 21 | errorName, 22 | actualErrorName 23 | ) 24 | 25 | if (params) { 26 | for (let i = 0; i < actualParams.length; i += 1) { 27 | this.assert( 28 | actualParams[i] === params[i], 29 | `Expected ${actualParams[i]} to be ${params[i]}`, 30 | `Expected ${actualParams[i]} NOT to be ${params[i]}`, 31 | params[i], 32 | actualParams[i] 33 | ) 34 | } 35 | } 36 | } 37 | }) 38 | } 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@primitivefi/rmm-examples", 3 | "version": "0.0.3", 4 | "description": "Example contracts showing how to interact with RMM protocol.", 5 | "keywords": [ 6 | "primitive", 7 | "v2", 8 | "amm", 9 | "defi", 10 | "arbitrum", 11 | "swap", 12 | "ethereum" 13 | ], 14 | "author": "Primitive", 15 | "license": "GPL-3.0-or-later", 16 | "homepage": "https://primitive.finance", 17 | "scripts": { 18 | "typechain": "hardhat typechain", 19 | "clean": "hardhat clean", 20 | "compile": "hardhat compile", 21 | "test": "hardhat test", 22 | "prettier": "prettier --write 'contracts/**/*.sol'" 23 | }, 24 | "dependencies": { 25 | "@openzeppelin/contracts": "^4.1.0", 26 | "@primitivefi/rmm-core": "^1.0.0", 27 | "@primitivefi/rmm-manager": "^1.0.0", 28 | "@primitivefi/rmm-math": "^2.0.0-beta.3", 29 | "web3-units": "^1.4.0" 30 | }, 31 | "devDependencies": { 32 | "@nomiclabs/hardhat-ethers": "^2.0.5", 33 | "@nomiclabs/hardhat-waffle": "^2.0.3", 34 | "@typechain/ethers-v5": "^7.1.0", 35 | "@typechain/hardhat": "^2.2.0", 36 | "@types/chai": "^4.2.21", 37 | "@types/mocha": "^9.0.0", 38 | "@types/node": "^16.9.4", 39 | "chai": "^4.3.4", 40 | "ethereum-waffle": "^3.4.0", 41 | "ethers": "^5.6.1", 42 | "hardhat": "^2.9.1", 43 | "prettier": "^2.5.1", 44 | "prettier-plugin-solidity": "^1.0.0-beta.19", 45 | "ts-generator": "^0.1.1", 46 | "ts-node": "^9.1.1", 47 | "typechain": "^5.1.2", 48 | "typescript": "^4.2.3" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /contracts/primitiveChef/RewardToken.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity 0.8.6; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | 6 | /// @title RewardToken Contract 7 | /// @notice Reward token distributed via a PrimitiveChef contract 8 | /// @author Primitive 9 | contract RewardToken is ERC20 { 10 | /// ERRORS /// 11 | 12 | /// @notice Thrown when the sender is not the `chef` address 13 | error NotChefError(); 14 | 15 | /// MODIFIERS /// 16 | 17 | /// @dev Restricts the call to the `chef` address 18 | modifier onlyChef() { 19 | if (msg.sender != chef) revert NotChefError(); 20 | _; 21 | } 22 | 23 | /// STORAGE VARIABLES /// 24 | 25 | /// @notice Address of the PrimitiveChef contract 26 | address public chef; 27 | 28 | /// EFFECT FUNCTIONS /// 29 | 30 | /// @param name_ Name of the reward token 31 | /// @param symbol_ Symbol of the reward token 32 | /// @param chef_ Address of the PrimitiveChef contract 33 | constructor( 34 | string memory name_, 35 | string memory symbol_, 36 | address chef_ 37 | ) ERC20(name_, symbol_) { 38 | chef = chef_; 39 | } 40 | 41 | /// @notice Mints `amount` of tokens to `to` 42 | /// @dev Can only be called by the PrimitiveChef 43 | /// @param to Address receiving the tokens 44 | /// @param amount Amount of tokens to mint 45 | function mint(address to, uint256 amount) external onlyChef { 46 | _mint(to, amount); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/shared/matchers/supportMargin.ts: -------------------------------------------------------------------------------- 1 | import { BigNumber, Contract } from 'ethers' 2 | 3 | // Chai matchers for the margins of the PrimitiveEngine 4 | 5 | export default function supportMargin(Assertion: Chai.AssertionStatic) { 6 | Assertion.addMethod( 7 | 'updateMargin', 8 | async function ( 9 | this: any, 10 | manager: Contract, 11 | account: string, 12 | engine: string, 13 | delRisky: BigNumber, 14 | riskyIncrease: boolean, 15 | delStable: BigNumber, 16 | stableIncrease: boolean 17 | ) { 18 | const oldMargin = await manager.margins(account, engine) 19 | await this._obj 20 | const newMargin = await manager.margins(account, engine) 21 | 22 | const expectedRisky = riskyIncrease ? oldMargin.balanceRisky.add(delRisky) : oldMargin.balanceRisky.sub(delRisky) 23 | const expectedStable = stableIncrease ? oldMargin.balanceStable.add(delStable) : oldMargin.balanceStable.sub(delStable) 24 | 25 | this.assert( 26 | newMargin.balanceRisky.eq(expectedRisky), 27 | `Expected ${newMargin.balanceRisky} to be ${expectedRisky} risky`, 28 | `Expected ${newMargin.balanceRisky} NOT to be ${expectedRisky} risky`, 29 | expectedRisky, 30 | newMargin.balanceRisky 31 | ) 32 | 33 | this.assert( 34 | newMargin.balanceStable.eq(expectedStable), 35 | `Expected ${newMargin.balanceStable} to be ${expectedStable} stable`, 36 | `Expected ${newMargin.balanceStable} NOT to be ${expectedStable} stable`, 37 | expectedStable, 38 | newMargin.balanceStable 39 | ) 40 | } 41 | ) 42 | } 43 | -------------------------------------------------------------------------------- /test/shared/matchers/supportPosition.ts: -------------------------------------------------------------------------------- 1 | import { BigNumber, Contract } from 'ethers' 2 | 3 | // Chai matchers for the positions of the PrimitiveEngine 4 | 5 | export default function supportPosition(Assertion: Chai.AssertionStatic) { 6 | Assertion.addMethod( 7 | 'increasePositionLiquidity', 8 | async function (this: any, manager: Contract, account: string, poolId: string, liquidity: BigNumber) { 9 | const oldPosition = await manager.balanceOf(account, poolId) 10 | await this._obj 11 | const newPosition = await manager.balanceOf(account, poolId) 12 | 13 | const expectedLiquidity = oldPosition.add(liquidity) 14 | 15 | this.assert( 16 | newPosition.eq(expectedLiquidity), 17 | `Expected ${newPosition} to be ${expectedLiquidity}`, 18 | `Expected ${newPosition} NOT to be ${expectedLiquidity}`, 19 | expectedLiquidity, 20 | newPosition 21 | ) 22 | } 23 | ) 24 | 25 | Assertion.addMethod( 26 | 'decreasePositionLiquidity', 27 | async function (this: any, manager: Contract, account: string, poolId: string, liquidity: BigNumber) { 28 | const oldPosition = await manager.balanceOf(account, poolId) 29 | await this._obj 30 | const newPosition = await manager.balanceOf(account, poolId) 31 | 32 | const expectedLiquidity = oldPosition.sub(liquidity) 33 | 34 | this.assert( 35 | newPosition.eq(expectedLiquidity), 36 | `Expected ${newPosition} to be ${expectedLiquidity}`, 37 | `Expected ${newPosition} NOT to be ${expectedLiquidity}`, 38 | expectedLiquidity, 39 | newPosition 40 | ) 41 | } 42 | ) 43 | } 44 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | import { Contract, BigNumber } from 'ethers'; 2 | import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers'; 3 | 4 | export interface Contracts { 5 | primitiveFactory: Contract; 6 | primitiveEngine: Contract; 7 | primitiveManager: Contract; 8 | weth: Contract; 9 | stable: Contract; 10 | risky: Contract; 11 | } 12 | 13 | export interface Wallets { 14 | deployer: SignerWithAddress; 15 | alice: SignerWithAddress; 16 | bob: SignerWithAddress; 17 | } 18 | 19 | declare module 'mocha' { 20 | export interface Context { 21 | contracts: Contracts; 22 | wallets: Wallets; 23 | } 24 | } 25 | 26 | declare global { 27 | export namespace Chai { 28 | interface Assertion { 29 | revertWithCustomError(errorName: string, params?: any[]): AsyncAssertion 30 | updateMargin( 31 | manager: Contract, 32 | account: string, 33 | engine: string, 34 | delRisky: BigNumber, 35 | riskyIncrease: boolean, 36 | delStable: BigNumber, 37 | stableIncrease: boolean 38 | ): AsyncAssertion 39 | increaseMargin( 40 | manager: Contract, 41 | account: string, 42 | engine: string, 43 | delRisky: BigNumber, 44 | delStable: BigNumber 45 | ): AsyncAssertion 46 | decreaseMargin( 47 | manager: Contract, 48 | account: string, 49 | engine: string, 50 | delRisky: BigNumber, 51 | delStable: BigNumber 52 | ): AsyncAssertion 53 | increasePositionLiquidity( 54 | manager: Contract, 55 | account: string, 56 | poolId: string, 57 | liquidity: BigNumber 58 | ): AsyncAssertion 59 | decreasePositionLiquidity( 60 | manager: Contract, 61 | account: string, 62 | poolId: string, 63 | liquidity: BigNumber 64 | ): AsyncAssertion 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | artifacts/ 2 | cache/ 3 | node_modules/ 4 | typechain/ 5 | 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | node_modules/ 47 | jspm_packages/ 48 | 49 | # TypeScript v1 declaration files 50 | typings/ 51 | 52 | # TypeScript cache 53 | *.tsbuildinfo 54 | 55 | # Optional npm cache directory 56 | .npm 57 | .npmrc 58 | 59 | # Optional eslint cache 60 | .eslintcache 61 | 62 | # Microbundle cache 63 | .rpt2_cache/ 64 | .rts2_cache_cjs/ 65 | .rts2_cache_es/ 66 | .rts2_cache_umd/ 67 | 68 | # Optional REPL history 69 | .node_repl_history 70 | 71 | # Output of 'npm pack' 72 | *.tgz 73 | 74 | # Yarn Integrity file 75 | .yarn-integrity 76 | 77 | # dotenv environment variables file 78 | .env 79 | .env.test 80 | 81 | # parcel-bundler cache (https://parceljs.org/) 82 | .cache 83 | 84 | # Next.js build output 85 | .next 86 | 87 | # Nuxt.js build / generate output 88 | .nuxt 89 | dist 90 | 91 | # Gatsby files 92 | .cache/ 93 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 94 | # https://nextjs.org/blog/next-9-1#public-directory-support 95 | # public 96 | 97 | # vuepress build output 98 | .vuepress/dist 99 | 100 | # Serverless directories 101 | .serverless/ 102 | 103 | # FuseBox cache 104 | .fusebox/ 105 | 106 | # DynamoDB Local files 107 | .dynamodb/ 108 | 109 | # TernJS port file 110 | .tern-port 111 | 112 | .vscode 113 | -------------------------------------------------------------------------------- /test/liquidityManager.ts: -------------------------------------------------------------------------------- 1 | import hre from 'hardhat'; 2 | import { constants, Contract } from 'ethers'; 3 | import { parseWei } from 'web3-units'; 4 | 5 | import { runTest } from './shared/fixture' 6 | import expect from './shared/expect'; 7 | import { DEFAULT_CALIBRATION } from './shared/config'; 8 | 9 | let liquidityManager: Contract; 10 | let poolId: string; 11 | 12 | runTest('LiquidityManager', function () { 13 | beforeEach(async function () { 14 | const LiquidityManager = await hre.ethers.getContractFactory('LiquidityManager'); 15 | 16 | liquidityManager = await LiquidityManager.deploy( 17 | this.contracts.primitiveManager.address, 18 | this.contracts.risky.address, 19 | this.contracts.stable.address, 20 | ); 21 | 22 | poolId = DEFAULT_CALIBRATION.poolId(this.contracts.primitiveEngine.address); 23 | }); 24 | 25 | describe('success cases', function () { 26 | it('allocates risky and stable into a pool', async function () { 27 | await this.contracts.risky.approve( 28 | liquidityManager.address, 29 | constants.MaxUint256, 30 | ); 31 | 32 | await this.contracts.stable.approve( 33 | liquidityManager.address, 34 | constants.MaxUint256, 35 | ); 36 | 37 | const delLiquidity = parseWei(1).raw; 38 | const res = await this.contracts.primitiveEngine.reserves(poolId) 39 | const delRisky = delLiquidity.mul(res.reserveRisky).div(res.liquidity) 40 | const delStable = delLiquidity.mul(res.reserveStable).div(res.liquidity) 41 | 42 | await liquidityManager.allocate( 43 | poolId, 44 | delRisky, 45 | delStable, 46 | delLiquidity, 47 | ); 48 | 49 | expect( 50 | await liquidityManager.liquidityOf(this.wallets.deployer.address) 51 | ).to.be.equal(delLiquidity); 52 | }); 53 | 54 | it('allocates and removes', async function () { 55 | await this.contracts.risky.approve( 56 | liquidityManager.address, 57 | constants.MaxUint256, 58 | ); 59 | 60 | await this.contracts.stable.approve( 61 | liquidityManager.address, 62 | constants.MaxUint256, 63 | ); 64 | 65 | const delLiquidity = parseWei(1).raw; 66 | const res = await this.contracts.primitiveEngine.reserves(poolId) 67 | const delRisky = delLiquidity.mul(res.reserveRisky).div(res.liquidity) 68 | const delStable = delLiquidity.mul(res.reserveStable).div(res.liquidity) 69 | 70 | await liquidityManager.allocate( 71 | poolId, 72 | delRisky, 73 | delStable, 74 | delLiquidity, 75 | ); 76 | 77 | expect( 78 | await liquidityManager.liquidityOf(this.wallets.deployer.address) 79 | ).to.be.equal(delLiquidity); 80 | }); 81 | }) 82 | }); 83 | -------------------------------------------------------------------------------- /test/shared/permit.ts: -------------------------------------------------------------------------------- 1 | import { Wallet, BigNumberish, Signature, utils } from 'ethers' 2 | import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers'; 3 | 4 | export async function getERC20PermitSignature( 5 | wallet: Wallet, 6 | token: string, 7 | spender: string, 8 | value: BigNumberish, 9 | deadline: BigNumberish, 10 | permitConfig: { 11 | nonce: BigNumberish 12 | name: string 13 | chainId: number 14 | version: string 15 | } 16 | ): Promise { 17 | return utils.splitSignature( 18 | await wallet._signTypedData( 19 | { 20 | name: permitConfig.name, 21 | version: permitConfig.version, 22 | chainId: permitConfig.chainId, 23 | verifyingContract: token, 24 | }, 25 | { 26 | Permit: [ 27 | { 28 | name: 'owner', 29 | type: 'address', 30 | }, 31 | { 32 | name: 'spender', 33 | type: 'address', 34 | }, 35 | { 36 | name: 'value', 37 | type: 'uint256', 38 | }, 39 | { 40 | name: 'nonce', 41 | type: 'uint256', 42 | }, 43 | { 44 | name: 'deadline', 45 | type: 'uint256', 46 | }, 47 | ], 48 | }, 49 | { 50 | owner: wallet.address, 51 | spender, 52 | value, 53 | nonce: permitConfig.nonce, 54 | deadline, 55 | } 56 | ) 57 | ) 58 | } 59 | 60 | export async function getERC1155PermitSignature( 61 | wallet: Wallet | SignerWithAddress, 62 | token: string, 63 | operator: string, 64 | approved: boolean, 65 | deadline: BigNumberish, 66 | permitConfig: { 67 | nonce: BigNumberish 68 | name: string 69 | chainId: number 70 | version: string 71 | } 72 | ): Promise { 73 | return utils.splitSignature( 74 | await wallet._signTypedData( 75 | { 76 | name: permitConfig.name, 77 | version: permitConfig.version, 78 | chainId: permitConfig.chainId, 79 | verifyingContract: token, 80 | }, 81 | { 82 | Permit: [ 83 | { 84 | name: 'owner', 85 | type: 'address', 86 | }, 87 | { 88 | name: 'operator', 89 | type: 'address', 90 | }, 91 | { 92 | name: 'approved', 93 | type: 'bool', 94 | }, 95 | { 96 | name: 'nonce', 97 | type: 'uint256', 98 | }, 99 | { 100 | name: 'deadline', 101 | type: 'uint256', 102 | }, 103 | ], 104 | }, 105 | { 106 | owner: wallet.address, 107 | operator, 108 | approved, 109 | nonce: permitConfig.nonce, 110 | deadline, 111 | } 112 | ) 113 | ) 114 | } 115 | -------------------------------------------------------------------------------- /contracts/liquidityWrapper/LiquidityWrapper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity 0.8.6; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | import "@primitivefi/rmm-manager/contracts/interfaces/IERC1155Permit.sol"; 6 | import "@primitivefi/rmm-manager/contracts/base/Multicall.sol"; 7 | import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; 8 | import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; 9 | 10 | import "./ILiquidityWrapper.sol"; 11 | 12 | /// @title Liquidity Wrapper contract 13 | /// @notice Allows users to wrap specific PrimitiveManager liquidity pool tokens 14 | /// (ERC1155) into ERC20 tokens 15 | /// @author Primitive 16 | contract LiquidityWrapper is 17 | ILiquidityWrapper, 18 | ERC20, 19 | ERC1155Holder, 20 | Multicall 21 | { 22 | /// STORAGE VARIABLES /// 23 | 24 | /// @inheritdoc ILiquidityWrapper 25 | address public override manager; 26 | 27 | /// @inheritdoc ILiquidityWrapper 28 | uint256 public override poolId; 29 | 30 | /// @dev Null variable to pass to `safeTransferFrom` 31 | bytes private empty; 32 | 33 | /// EFFECT FUNCTIONS /// 34 | 35 | /// @param name_ Name of the wrapped token 36 | /// @param symbol_ Symbol of the wrapped token 37 | /// @param manager_ Address of the PrimitiveManager associated with this wrapper 38 | /// @param poolId_ Id of the PrimitiveManager liquidity pool token associated with this wrapper 39 | constructor( 40 | string memory name_, 41 | string memory symbol_, 42 | address manager_, 43 | uint256 poolId_ 44 | ) ERC20(name_, symbol_) { 45 | manager = manager_; 46 | poolId = poolId_; 47 | } 48 | 49 | /// @inheritdoc ILiquidityWrapper 50 | function selfPermit( 51 | address owner, 52 | bool approved, 53 | uint256 deadline, 54 | uint8 v, 55 | bytes32 r, 56 | bytes32 s 57 | ) external override { 58 | IERC1155Permit(manager).permit( 59 | owner, 60 | address(this), 61 | approved, 62 | deadline, 63 | v, 64 | r, 65 | s 66 | ); 67 | } 68 | 69 | /// @inheritdoc ILiquidityWrapper 70 | function wrap(address to, uint256 amount) external override { 71 | IERC1155(manager).safeTransferFrom( 72 | msg.sender, 73 | address(this), 74 | poolId, 75 | amount, 76 | empty 77 | ); 78 | _mint(to, amount); 79 | emit Wrap(msg.sender, to, amount); 80 | } 81 | 82 | /// @inheritdoc ILiquidityWrapper 83 | function unwrap(address to, uint256 amount) external override { 84 | _burn(msg.sender, amount); 85 | IERC1155(manager).safeTransferFrom( 86 | address(this), 87 | to, 88 | poolId, 89 | amount, 90 | empty 91 | ); 92 | emit Unwrap(msg.sender, to, amount); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /contracts/liquidityManager/ILiquidityManager.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity >=0.8.6; 3 | 4 | /// @title Liquidity Manager Interface 5 | /// @notice Shows how a contract can allocate and remove liquidity from RMM pools 6 | /// on behalf of users. This example focuses on interacting with a unique 7 | /// PrimitiveManager contract and only allows the deposit of a specific 8 | /// risky / stable pair 9 | /// @author Primitive 10 | interface ILiquidityManager { 11 | /// EFFECT FUNCTIONS /// 12 | 13 | /// @notice Allocates risky and stable tokens from the 14 | /// sender's wallet into a pool 15 | /// @param poolId Id of the pool to allocate the tokens into 16 | /// @param delRisky Amount of risky tokens to allocate into the pool 17 | /// @param delStable Amount of stable tokens to allocate into the pool 18 | /// @param minLiquidityOut Minimum amount of liquidity pool tokens expected 19 | /// to be received after the allocation 20 | function allocate( 21 | bytes32 poolId, 22 | uint256 delRisky, 23 | uint256 delStable, 24 | uint256 minLiquidityOut 25 | ) external; 26 | 27 | /// @notice Removes risky and stable tokens from a pool and sends 28 | /// them to the sender's wallet 29 | /// @param engine Address of the PrimitiveEngine contract specific to the 30 | /// risky / stable pair 31 | /// @param poolId Id of the pool to remove the liquidity tokens from 32 | /// @param delLiquidity Amount of liquidity pool tokens to remove 33 | /// @param minRiskyOut Minimum amount of risky tokens expected to be received 34 | /// after the removal 35 | /// @param minStableOut Minimum amount of stable tokens expected to be received 36 | /// after the removal 37 | function remove( 38 | address engine, 39 | bytes32 poolId, 40 | uint256 delLiquidity, 41 | uint256 minRiskyOut, 42 | uint256 minStableOut 43 | ) external; 44 | 45 | /// VIEW FUNCTIONS /// 46 | 47 | /// @notice PrimitiveManager contract used to allocate and remove liquidity 48 | /// @return Address of the PrimitiveManager contract 49 | function manager() external view returns (address); 50 | 51 | /// @notice Risky token of the risky / stable pair 52 | /// @return Address of the risky token contract 53 | function risky() external view returns (address); 54 | 55 | /// @notice Stable token of the risky / stable pair 56 | /// @return Address of the stable token contract 57 | function stable() external view returns (address); 58 | 59 | /// @notice Amount of liquidity pool tokens currently owned by 60 | /// a user and managed by the LiquidityManager contract 61 | /// @return Amount of liquidity pool tokens 62 | function liquidityOf(address) external view returns (uint256); 63 | } 64 | -------------------------------------------------------------------------------- /contracts/liquidityWrapper/ILiquidityWrapper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity >=0.8.6; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import "@primitivefi/rmm-manager/contracts/interfaces/IMulticall.sol"; 6 | import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; 7 | 8 | /// @title Liquidity Wrapper Interface 9 | /// @notice Allows users to wrap specific PrimitiveManager liquidity pool tokens 10 | /// (ERC1155) into ERC20 tokens 11 | /// @author Primitive 12 | interface ILiquidityWrapper is IERC20, IERC1155Receiver, IMulticall { 13 | /// EVENTS /// 14 | 15 | /// @notice Emitted when `from` wraps `amount` of liquidity pool tokens for `to` 16 | /// @param from Address wrapping the liquidity pool tokens 17 | /// @param to Address receiving the wrapped liquidity pool tokens 18 | /// @param amount Amount of liquidity pool tokens wrapped 19 | event Wrap(address indexed from, address indexed to, uint256 amount); 20 | 21 | /// @notice Emitted when `from` unwraps `amount` liquidity pool tokens for `to` 22 | /// @param from Address unwrapping the liquidity pool tokens 23 | /// @param to Address receiving the unwrapped liquidity pool tokens 24 | /// @param amount Amount of liquidity pool tokens unwrapped 25 | event Unwrap(address indexed from, address indexed to, uint256 amount); 26 | 27 | /// EFFECT FUNCTIONS /// 28 | 29 | /// @notice Self approves the wrapper to move `owner` liquidity pool tokens by using permit 30 | /// @param owner Address of the owner of the liquidity pool tokens 31 | /// @param approved True if the approval should be granted 32 | /// @param deadline Expiry date of the signature 33 | /// @param v V part of the signature 34 | /// @param r R part of the signature 35 | /// @param s S part of the signature 36 | function selfPermit( 37 | address owner, 38 | bool approved, 39 | uint256 deadline, 40 | uint8 v, 41 | bytes32 r, 42 | bytes32 s 43 | ) external; 44 | 45 | /// @notice Wraps `amount` of liquidity pool tokens and sends them to `to` 46 | /// @param to Address of the recipient of the wrapped liquidity pool tokens 47 | /// @param amount Amount of liquidity pool tokens to wrap 48 | function wrap(address to, uint256 amount) external; 49 | 50 | /// @notice Unwraps `amount` of wrapped liquidity pool tokens and sends them to {to} 51 | /// @param to Address of the recipient of the unwrapped liquidity pool tokens 52 | /// @param amount Amount of wrapped liquidity pool tokens to unwrap 53 | function unwrap(address to, uint256 amount) external; 54 | 55 | /// VIEW FUNCTIONS /// 56 | 57 | /// @notice Returns the address of the PrimitiveManager associated with this wrapper 58 | /// @return Address of the PrimitiveManager associated with this wrapper 59 | function manager() external view returns (address); 60 | 61 | /// @notice Returns the id of the PrimitiveManager liquidity pool token pool associated with this wrapper 62 | /// @return Id of the PrimitiveManager liquidity pool token associated with this wrapper 63 | function poolId() external view returns (uint256); 64 | } 65 | -------------------------------------------------------------------------------- /contracts/liquidityManager/LiquidityManager.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | pragma solidity 0.8.9; 3 | 4 | import "@primitivefi/rmm-manager/contracts/interfaces/IPrimitiveManager.sol"; 5 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 6 | import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; 7 | 8 | import "./ILiquidityManager.sol"; 9 | 10 | /// @title Liquidity Manager contract 11 | /// @notice Shows how a contract can allocate and remove liquidity from RMM pools 12 | /// on behalf of users. This example focuses on interacting with a unique 13 | /// PrimitiveManager contract and only allows the deposit of a specific 14 | /// risky / stable pair 15 | /// @author Primitive 16 | contract LiquidityManager is ILiquidityManager, ERC1155Holder { 17 | /// STORAGE VARIABLES /// 18 | 19 | /// @inheritdoc ILiquidityManager 20 | address public manager; 21 | 22 | /// @inheritdoc ILiquidityManager 23 | address public risky; 24 | 25 | /// @inheritdoc ILiquidityManager 26 | address public stable; 27 | 28 | /// @inheritdoc ILiquidityManager 29 | mapping(address => uint256) public liquidityOf; 30 | 31 | /// EFFECT FUNCTIONS /// 32 | 33 | /// @param manager_ Address of the PrimitiveManager contract that this contract 34 | /// will interfact with 35 | /// @param risky_ Address of the risky token contract of the risky / stable pair 36 | /// @param stable_ Address of the stable token contract of the risky / stable pair 37 | constructor( 38 | address manager_, 39 | address risky_, 40 | address stable_ 41 | ) { 42 | manager = manager_; 43 | risky = risky_; 44 | stable = stable_; 45 | 46 | IERC20(risky).approve(manager, type(uint256).max); 47 | IERC20(stable).approve(manager, type(uint256).max); 48 | } 49 | 50 | /// @inheritdoc ILiquidityManager 51 | function allocate( 52 | bytes32 poolId, 53 | uint256 delRisky, 54 | uint256 delStable, 55 | uint256 minLiquidityOut 56 | ) external { 57 | IERC20(risky).transferFrom(msg.sender, address(this), delRisky); 58 | IERC20(stable).transferFrom(msg.sender, address(this), delStable); 59 | 60 | uint256 delLiquidity = IPrimitiveManager(manager).allocate( 61 | address(this), 62 | poolId, 63 | risky, 64 | stable, 65 | delRisky, 66 | delStable, 67 | false, 68 | minLiquidityOut 69 | ); 70 | 71 | liquidityOf[msg.sender] += delLiquidity; 72 | 73 | uint256 dust = IERC20(risky).balanceOf(address(this)); 74 | if (dust != 0) IERC20(risky).transfer(msg.sender, dust); 75 | 76 | dust = IERC20(stable).balanceOf(address(this)); 77 | if (dust != 0) IERC20(stable).transfer(msg.sender, dust); 78 | } 79 | 80 | /// @inheritdoc ILiquidityManager 81 | function remove( 82 | address engine, 83 | bytes32 poolId, 84 | uint256 delLiquidity, 85 | uint256 minRiskyOut, 86 | uint256 minStableOut 87 | ) external { 88 | liquidityOf[msg.sender] -= delLiquidity; 89 | 90 | (uint256 delRisky, uint256 delStable) = IPrimitiveManager(manager) 91 | .remove(engine, poolId, delLiquidity, minRiskyOut, minStableOut); 92 | 93 | if (delRisky != 0) IERC20(risky).transfer(msg.sender, delRisky); 94 | if (delStable != 0) IERC20(stable).transfer(msg.sender, delStable); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /test/shared/fixture.ts: -------------------------------------------------------------------------------- 1 | import hre, { ethers } from 'hardhat'; 2 | import { constants, Wallet, } from 'ethers'; 3 | import { parseWei } from 'web3-units'; 4 | import { createFixtureLoader, MockProvider } from 'ethereum-waffle'; 5 | 6 | import PrimitiveFactoryArtifact from '@primitivefi/rmm-core/artifacts/contracts/PrimitiveFactory.sol/PrimitiveFactory.json'; 7 | import PrimitiveEngineArtifact from '@primitivefi/rmm-core/artifacts/contracts/PrimitiveEngine.sol/PrimitiveEngine.json'; 8 | import PrimitiveManagerArtifact from '@primitivefi/rmm-manager/artifacts/contracts/PrimitiveManager.sol/PrimitiveManager.json'; 9 | 10 | import { computeEngineAddress } from './utils'; 11 | import { DEFAULT_CALIBRATION } from './config'; 12 | 13 | export function runTest(description: string, runTests: Function): void { 14 | describe(description, function () { 15 | beforeEach(async function () { 16 | const wallets = await hre.ethers.getSigners(); 17 | const [deployer, alice, bob] = wallets; 18 | const loadFixture = createFixtureLoader(wallets as unknown as Wallet[]); 19 | const loadedFixture = await loadFixture(fixture); 20 | 21 | this.contracts = { 22 | primitiveFactory: loadedFixture.primitiveFactory, 23 | primitiveEngine: loadedFixture.primitiveEngine, 24 | primitiveManager: loadedFixture.primitiveManager, 25 | weth: loadedFixture.weth, 26 | risky: loadedFixture.risky, 27 | stable: loadedFixture.stable, 28 | }; 29 | 30 | this.wallets = { 31 | deployer, 32 | alice, 33 | bob, 34 | }; 35 | }); 36 | 37 | runTests(); 38 | }) 39 | } 40 | 41 | export async function fixture([deployer]: Wallet[], provider: MockProvider) { 42 | const PrimitiveFactory = await ethers.getContractFactory( 43 | PrimitiveFactoryArtifact.abi, 44 | PrimitiveFactoryArtifact.bytecode, 45 | deployer, 46 | ); 47 | const primitiveFactory = await PrimitiveFactory.deploy(); 48 | 49 | const TestERC20 = await ethers.getContractFactory('TestERC20', deployer); 50 | const risky = await TestERC20.deploy(); 51 | const stable = await TestERC20.deploy(); 52 | 53 | await primitiveFactory.deploy(risky.address, stable.address); 54 | 55 | 56 | const engineAddress = computeEngineAddress( 57 | primitiveFactory.address, 58 | risky.address, 59 | stable.address, 60 | PrimitiveEngineArtifact.bytecode, 61 | ) 62 | 63 | const primitiveEngine = await ethers.getContractAt(PrimitiveEngineArtifact.abi, engineAddress, deployer); 64 | 65 | const Weth = await ethers.getContractFactory('WETH9', deployer); 66 | const weth = await Weth.deploy(); 67 | 68 | const PrimitiveManager = await ethers.getContractFactory( 69 | PrimitiveManagerArtifact.abi, 70 | PrimitiveManagerArtifact.bytecode, 71 | deployer 72 | ); 73 | 74 | const primitiveManager = await PrimitiveManager.deploy( 75 | primitiveFactory.address, 76 | weth.address, 77 | weth.address, 78 | ); 79 | 80 | await risky.mint(deployer.address, parseWei('1000000').raw) 81 | await stable.mint(deployer.address, parseWei('1000000').raw) 82 | await risky.approve(primitiveManager.address, constants.MaxUint256) 83 | await stable.approve(primitiveManager.address, constants.MaxUint256) 84 | 85 | await primitiveManager.create( 86 | risky.address, 87 | stable.address, 88 | DEFAULT_CALIBRATION.strike.raw, 89 | DEFAULT_CALIBRATION.sigma.raw, 90 | DEFAULT_CALIBRATION.maturity.raw, 91 | DEFAULT_CALIBRATION.gamma.raw, 92 | parseWei(1).sub(parseWei(DEFAULT_CALIBRATION.delta)).raw, 93 | parseWei(1).raw, 94 | ) 95 | 96 | return { 97 | primitiveFactory, 98 | primitiveEngine, 99 | primitiveManager, 100 | weth, 101 | risky, 102 | stable, 103 | }; 104 | } 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](https://pbs.twimg.com/profile_banners/1241234631707381760/1588727988/1500x500) 2 | 3 | # 🦣 RMM Examples 4 | 5 | [![License](https://img.shields.io/badge/License-GPLv3-green.svg)](https://www.gnu.org/licenses/gpl-3.0) 6 | 7 | This repository contains examples showing how to interact with the RMM protocol. 8 | 9 | Alternatively, you can use this repository as a base if you plan on building on top of the RMM protocol, as it contains all the necessary setup to run the whole protocol locally. 10 | 11 | > ⚠️ These example contracts are written for educational purposes and were **NOT AUDITED**. Keep this in mind before using them in production. 12 | 13 | ## 🚀 Usage 14 | 15 | Clone the repository on your computer: 16 | 17 | ```bash 18 | git clone https://github.com/primitivefinance/rmm-examples.git 19 | ``` 20 | 21 | Then install the required dependencies: 22 | 23 | ```bash 24 | # Using npm 25 | npm install 26 | 27 | # Using yarn 28 | yarn 29 | ``` 30 | 31 | After that, you can try the other commands: 32 | 33 | ```bash 34 | # Using npm and npx 35 | 36 | # Compile the contracts 37 | npm run compile 38 | 39 | # Run a test 40 | npx hardhat test ./path/to/the/test.ts 41 | 42 | # Style the contracts using Prettier 43 | npm run prettier 44 | 45 | 46 | # Using yarn 47 | 48 | # Compile the contracts 49 | yarn compile 50 | 51 | # Run a test 52 | yarn hardhat test ./path/to/the/test.ts 53 | 54 | # Style the contracts using Prettier 55 | yarn prettier 56 | ``` 57 | 58 | ## 📚 Example Contracts 59 | 60 | ### 💦 LiquidityManager 61 | 62 | This simple example shows how a contract can manage liquidity pool tokens on the behalf of users, allowing them to allocate or remove into different pools. It's a very basic version of the `PrimitiveManager` contract. 63 | 64 | The features of this example are quite basic: 65 | - Users can allocate or remove liquidity into a pool of a predefined risky / stable pair 66 | - Check the liquidity of each user currently managed by the contract 67 | 68 | See the code [here](contracts/liquidityManager/liquidityManager.sol). 69 | 70 | ### 🎁 LiquidityWrapper 71 | 72 | The PrimitiveManager contract tokenizes liquidity pool tokens using the ERC1155 standard. This allows significant gas optimizations at a contract level, but adds a little bit of friction when it comes to integrating with other protocols, more used to deal with ERC20 tokens. Luckily, a straightforward solution to this problem is to use a "wrapper" contract. 73 | 74 | The specifications of the `LiquidityWrapper` contract are extremely simple: 75 | - A wrapper can only be associated with a unique PrimitiveManager token id (a specific pool) 76 | - Deposit (wrap) liquidity pool tokens (ERC1155) to receive wrapped tokens (ERC20) 77 | - Withdraw (unwrap) wrapped liquidity pool tokens (ERC20) to get their unwrapped tokens back (ERC1155) 78 | 79 | See the code [here](contracts/liquidityWrapper/LiquidityWrapper.sol). 80 | 81 | ### 🧑‍🍳 PrimitiveChef 82 | 83 | Based on the [MasterChef](https://github.com/sushiswap/sushiswap/blob/canary/contracts/MasterChef.sol) created by SushiSwap, this contract is a reimplementation of the code with the support of ERC1155 tokens, the token standard used by the PrimitiveManager. 84 | 85 | In a few words, the `PrimitiveChef` goals are to: 86 | - Create staking pools dedicated to specific ERC1155 tokens 87 | - Reward users depositing liquidity pool tokens in these staking pools 88 | 89 | See the code [here](contracts/primitiveChef/PrimitiveChef.sol). 90 | 91 | ## 🏗 Building 92 | 93 | As mentioned above, if you plan on building on top of the RMM protocol, this repository can be used as a base for your work, as it already contains: 94 | - A local context deploying a complete version of the protocol (PrimitiveFactory, PrimitiveEngine, PrimitiveManager and test ERC20 tokens) 95 | - Custom Mocha hooks specific to the RMM protocol 96 | 97 | Feel free to remove the examples or any files you don't want to keep to make yourself at home! 98 | -------------------------------------------------------------------------------- /test/shared/calibration.ts: -------------------------------------------------------------------------------- 1 | import { parseWei, Percentage, Time, Wei, toBN, parsePercentage } from 'web3-units' 2 | import { callDelta, callPremium } from '@primitivefi/rmm-math' 3 | 4 | import { computePoolId } from './utils' 5 | 6 | /** 7 | * @notice Calibration Struct; Class representation of each Curve's parameters 8 | */ 9 | export class Calibration { 10 | /** 11 | * @notice Strike price with decimals = stable decimals 12 | */ 13 | public readonly strike: Wei 14 | /** 15 | * @notice Volatility as a Percentage instance with 4 decimals 16 | */ 17 | public readonly sigma: Percentage 18 | /** 19 | * @notice Time class with a raw value in seconds 20 | */ 21 | public readonly maturity: Time 22 | /** 23 | * @notice Time until expiry is calculated from the difference of current timestamp and this 24 | */ 25 | public readonly lastTimestamp: Time 26 | /** 27 | * @notice Price of risky token in stable token units with precision stable decimals 28 | */ 29 | public readonly spot: Wei 30 | /** 31 | * @notice Gamma is applied on input amounts to apply the swap fee, equal to 1 - fee % 32 | */ 33 | public readonly gamma: Percentage 34 | /** 35 | * @notice Decimals of risky asset 36 | */ 37 | public readonly decimalsRisky: number 38 | /** 39 | * @notice Decimals of stable asset 40 | */ 41 | public readonly decimalsStable: number 42 | 43 | /** 44 | * 45 | * @param strike Strike price as a float 46 | * @param sigma Volatility percentage as a float, e.g. 1 = 100% 47 | * @param maturity Timestamp in seconds 48 | * @param lastTimestamp Timestamp in seconds 49 | * @param spot Value of risky asset in units of riskless asset 50 | */ 51 | constructor( 52 | strike: number, 53 | sigma: number, 54 | maturity: number, 55 | lastTimestamp: number, 56 | spot: number, 57 | gamma: Percentage = new Percentage(toBN(0)), 58 | decimalsRisky: number = 18, 59 | decimalsStable: number = 18 60 | ) { 61 | this.strike = parseWei(strike, decimalsStable) 62 | this.sigma = parsePercentage(sigma) 63 | this.maturity = new Time(maturity) // in seconds, because `block.timestamp` is in seconds 64 | this.lastTimestamp = new Time(lastTimestamp) // in seconds, because `block.timestamp` is in seconds 65 | this.spot = parseWei(spot, decimalsStable) 66 | this.gamma = gamma 67 | this.decimalsRisky = decimalsRisky 68 | this.decimalsStable = decimalsStable 69 | } 70 | 71 | /** 72 | * @notice Scaling factor of risky asset, 18 - risky decimals 73 | */ 74 | get scaleFactorRisky(): number { 75 | return 18 - this.decimalsRisky 76 | } 77 | 78 | /** 79 | * @notice Scaling factor of stable asset, 18 - stable decimals 80 | */ 81 | get scaleFactorStable(): number { 82 | return 18 - this.decimalsStable 83 | } 84 | 85 | get MIN_LIQUIDITY(): number { 86 | return (this.decimalsStable > this.decimalsRisky ? this.decimalsRisky : this.decimalsStable) / 6 87 | } 88 | 89 | /** 90 | * @returns Time until expiry 91 | */ 92 | get tau(): Time { 93 | return this.maturity.sub(this.lastTimestamp) 94 | } 95 | 96 | /** 97 | * @returns Change in pool premium wrt change in underlying spot price 98 | */ 99 | get delta(): number { 100 | return callDelta(this.strike.float, this.sigma.float, this.tau.years, this.spot.float) 101 | } 102 | 103 | /** 104 | * @returns Black-Scholes implied premium 105 | */ 106 | get premium(): number { 107 | return callPremium(this.strike.float, this.sigma.float, this.tau.years, this.spot.float) 108 | } 109 | 110 | /** 111 | * @returns Spot price is above strike price 112 | */ 113 | get inTheMoney(): boolean { 114 | return this.strike.float >= this.spot.float 115 | } 116 | 117 | poolId(engine: string): string { 118 | return computePoolId(engine, this.maturity.raw, this.sigma.raw, this.strike.raw, this.gamma.raw) 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /test/liquidityWrapper.ts: -------------------------------------------------------------------------------- 1 | import hre, { ethers } from 'hardhat'; 2 | import { Contract } from 'ethers'; 3 | import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers'; 4 | 5 | import expect from './shared/expect'; 6 | import { getERC1155PermitSignature } from './shared/permit'; 7 | 8 | import { TestERC1155Permit, LiquidityWrapper } from '../typechain'; 9 | 10 | let lpToken: TestERC1155Permit; 11 | let wrappedLpToken: LiquidityWrapper; 12 | let signers: SignerWithAddress[]; 13 | let deployer: SignerWithAddress; 14 | 15 | let poolId = 0; 16 | 17 | async function deploy(contractName: string, deployer: SignerWithAddress, args: any[] = []): Promise { 18 | const artifact = await hre.artifacts.readArtifact(contractName) 19 | const contract = await hre.waffle.deployContract(deployer, artifact, args, { gasLimit: 9500000 }) 20 | return contract 21 | } 22 | 23 | describe('LiquidityWrapper', () => { 24 | beforeEach(async () => { 25 | signers = await ethers.getSigners(); 26 | [deployer] = signers; 27 | 28 | lpToken = await deploy('TestERC1155Permit', deployer) as TestERC1155Permit; 29 | 30 | wrappedLpToken = await deploy('LiquidityWrapper', deployer, [ 31 | 'NAME', 32 | 'SYMBOL', 33 | lpToken.address, 34 | poolId, 35 | ]) as LiquidityWrapper; 36 | 37 | await lpToken.mint(deployer.address, poolId, 100); 38 | }); 39 | 40 | describe('success cases', () => { 41 | describe('when wrapping liquidity pool tokens', () => { 42 | it('wraps liquidity pool tokens', async () => { 43 | await lpToken.setApprovalForAll(wrappedLpToken.address, true); 44 | await wrappedLpToken.wrap(deployer.address, 100); 45 | 46 | expect(await wrappedLpToken.balanceOf(deployer.address)).to.be.equal(100); 47 | expect(await lpToken.balanceOf(deployer.address, poolId)).to.be.equal(0); 48 | expect(await lpToken.balanceOf(wrappedLpToken.address, poolId)).to.be.equal(100); 49 | }); 50 | 51 | it('emits the Wrap event', async () => { 52 | await lpToken.setApprovalForAll(wrappedLpToken.address, true); 53 | await expect(wrappedLpToken.wrap(deployer.address, 100)).to.emit(wrappedLpToken, 'Wrap').withArgs( 54 | deployer.address, deployer.address, 100, 55 | ); 56 | }); 57 | 58 | it('wraps liquidity pool tokens (using the Multicall)', async () => { 59 | const sig = await getERC1155PermitSignature( 60 | deployer, 61 | lpToken.address, 62 | wrappedLpToken.address, 63 | true, 64 | 999999999999999, { 65 | nonce: 0, 66 | name: 'PrimitiveManager', 67 | chainId: await deployer.getChainId(), 68 | version: '1', 69 | }, 70 | ); 71 | 72 | const selfPermitData = wrappedLpToken.interface.encodeFunctionData( 73 | 'selfPermit', [ 74 | deployer.address, 75 | true, 76 | 999999999999999, 77 | sig.v, 78 | sig.r, 79 | sig.s 80 | ], 81 | ); 82 | 83 | const wrapData = wrappedLpToken.interface.encodeFunctionData( 84 | 'wrap', [ 85 | deployer.address, 86 | 100, 87 | ], 88 | ); 89 | 90 | await wrappedLpToken.multicall([selfPermitData, wrapData]); 91 | 92 | expect(await wrappedLpToken.balanceOf(deployer.address)).to.be.equal(100); 93 | expect(await lpToken.balanceOf(deployer.address, poolId)).to.be.equal(0); 94 | expect(await lpToken.balanceOf(wrappedLpToken.address, poolId)).to.be.equal(100); 95 | }); 96 | }); 97 | 98 | describe('when unwrapping liquidity pool tokens', () => { 99 | beforeEach(async () => { 100 | await lpToken.setApprovalForAll(wrappedLpToken.address, true); 101 | await wrappedLpToken.wrap(deployer.address, 100); 102 | }); 103 | 104 | it('unwraps liquidity pool tokens', async () => { 105 | await wrappedLpToken.unwrap(deployer.address, 100); 106 | 107 | expect(await wrappedLpToken.balanceOf(deployer.address)).to.be.equal(0); 108 | expect(await lpToken.balanceOf(deployer.address, poolId)).to.be.equal(100); 109 | expect(await lpToken.balanceOf(wrappedLpToken.address, poolId)).to.be.equal(0); 110 | }); 111 | 112 | it('emits the Unwrap event', async () => { 113 | await expect(wrappedLpToken.unwrap(deployer.address, 100)).to.emit(wrappedLpToken, 'Unwrap').withArgs( 114 | deployer.address, deployer.address, 100, 115 | ) 116 | }); 117 | }); 118 | }); 119 | 120 | describe('fail cases', () => { 121 | it('fails to wrap more than the balance', async () => { 122 | await lpToken.connect(signers[1]).setApprovalForAll(wrappedLpToken.address, true); 123 | 124 | await expect( 125 | wrappedLpToken.wrap(signers[1].address, 100), 126 | ).to.be.reverted 127 | }); 128 | 129 | it('fails to unwrap more than the balance', async () => { 130 | await lpToken.setApprovalForAll(wrappedLpToken.address, true); 131 | await wrappedLpToken.wrap(deployer.address, 100); 132 | 133 | await expect( 134 | wrappedLpToken.unwrap(deployer.address, 101), 135 | ).to.be.reverted 136 | }); 137 | }); 138 | }); 139 | -------------------------------------------------------------------------------- /contracts/primitiveChef/IPrimitiveChef.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.8.6; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; 6 | import "@openzeppelin/contracts/access/Ownable.sol"; 7 | import "@primitivefi/rmm-manager/contracts/interfaces/IERC1155Permit.sol"; 8 | import "@primitivefi/rmm-manager/contracts/interfaces/IMulticall.sol"; 9 | import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; 10 | import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; 11 | 12 | import "./RewardToken.sol"; 13 | 14 | /// @title PrimitiveChef Interface 15 | /// @notice Updated version of SushiSwap MasterChef contract to support Primitive liquidity tokens. 16 | /// Along a couple of improvements, the biggest change is the support of ERC1155 instead of ERC20. 17 | /// @author Primitive 18 | interface IPrimitiveChef is IMulticall { 19 | /// STRUCTS /// 20 | 21 | /// @notice Info of a user 22 | /// @return amount Amount of liquidity pool tokens provided by the user 23 | /// @return rewardDebt Pending reward debt of the user 24 | struct UserInfo { 25 | uint256 amount; 26 | uint256 rewardDebt; 27 | } 28 | 29 | /// @notice Info of a staking pool 30 | /// @return lpToken Address of the PrimitiveManager contract 31 | /// @return tokenId Id of the PrimitiveManager pool 32 | /// @return allocPoinnt Allocation points assigned to this pool 33 | /// @return lastRewardBlock Last block number with a reward distribution 34 | /// @return accRewardPerShare Accumulated reward per share with a 1e12 precision 35 | struct PoolInfo { 36 | IERC1155 lpToken; 37 | uint256 tokenId; 38 | uint256 allocPoint; 39 | uint256 lastRewardBlock; 40 | uint256 accRewardPerShare; 41 | } 42 | 43 | /// EVENTS /// 44 | 45 | /// @notice Emitted when a user deposits liquidity pool tokens in a staking pool 46 | /// @param user Address of the user depositing into the staking pool 47 | /// @param pid Id of the staking pool 48 | /// @param amount Amount of liquidity pool tokens deposited into the staking pool 49 | event Deposit(address indexed user, uint256 indexed pid, uint256 amount); 50 | 51 | /// @notice Emitted when a user withdraws liquidity pool tokens from a staking pool 52 | /// @param user Address of the user withdrawing from the staking pool 53 | /// @param pid Id of the staking pool 54 | /// @param amount Amount of liquidity tokens withdrawn from the staking pool 55 | event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); 56 | 57 | /// @notice Emitted when a user emergency withdraws liquidity pool tokens from a staking pool 58 | /// @param user Address of the user emergency withdrawing from the staking pool 59 | /// @param pid Id of the staking pool 60 | event EmergencyWithdraw( 61 | address indexed user, 62 | uint256 indexed pid, 63 | uint256 amount 64 | ); 65 | 66 | /// ERRORS /// 67 | 68 | /// @notice Thrown when a user tries to withdraw more liquidity pool tokens than what they staked 69 | error WithdrawAmountError(); 70 | 71 | /// EFFECT FUNCTIONS /// 72 | 73 | /// @notice Self approves this contract to move {lpToken} liquidity pool tokens from {owner}'s wallet 74 | /// @param lpToken Address of the PrimitiveManager contract 75 | /// @param owner Address of the owner of the tokens 76 | /// @param approved True if approval should be granted 77 | /// @param v V part of the signature 78 | /// @param r R part of the signature 79 | /// @param s S part of the signature 80 | function selfPermit( 81 | address lpToken, 82 | address owner, 83 | bool approved, 84 | uint256 deadline, 85 | uint8 v, 86 | bytes32 r, 87 | bytes32 s 88 | ) external; 89 | 90 | /// @notice Adds a new liquidity pool token to the contract 91 | /// @dev Adding the same PrDo not add the same liquidity pool token twice, or this will mess up the reward calculations 92 | /// @param allocPoint Allocation points for this staking pool 93 | /// @param lpToken Address of the PrimitiveManager 94 | /// @param tokenId Id of the PrimitiveManager pool 95 | /// @param withUpdate True if the reward variables of the pool should be updated 96 | function add( 97 | uint256 allocPoint, 98 | IERC1155 lpToken, 99 | uint256 tokenId, 100 | bool withUpdate 101 | ) external; 102 | 103 | /// @notice Updates the allocation points of a pool 104 | /// @param pid Id of the pool to update 105 | /// @param allocPoint New allocation points for the pool 106 | /// @param withUpdate True if the reward variables of the pool should be updated 107 | function set( 108 | uint256 pid, 109 | uint256 allocPoint, 110 | bool withUpdate 111 | ) external; 112 | 113 | /// @notice Mass updates the reward variables for all the pools 114 | function massUpdatePools() external; 115 | 116 | /// @notice Updates the reward variables of a given pool 117 | /// @param pid Id of the poold to update 118 | function updatePool(uint256 pid) external; 119 | 120 | /// @notice Deposits {amount} of liquidity pool tokens into pool {pid} 121 | /// @param pid Id of the pool to deposit into 122 | /// @param amount Amount of liquidity pool tokens to deposit into the pool 123 | function deposit(uint256 pid, uint256 amount) external; 124 | 125 | /// @notice Withdraws {amount} of liquidity pool tokens from pool {poolId} 126 | /// @param pid Id of the pool to withdraw from 127 | /// @param amount Amount of liquidity pool tokens to withdraw from the pool 128 | function withdraw(uint256 pid, uint256 amount) external; 129 | 130 | /// @notice Emergency withdraws all the liquidity pool tokens from pool {poolId}, 131 | /// without getting the reward 132 | /// @param pid Id of the pool to emergency withdraw from 133 | function emergencyWithdraw(uint256 pid) external; 134 | 135 | /// @notice Sets the address of the dev bonus collector 136 | /// @param newCollector Address of the new collector 137 | function setCollector(address newCollector) external; 138 | 139 | /// VIEW FUNCTIONS /// 140 | 141 | /// @notice Returns the token rewarded to the stakers 142 | /// @return Contract of the reward token 143 | function rewardToken() external view returns (RewardToken); 144 | 145 | /// @notice Returns the address collecting the dev bonus 146 | /// @return Address of the collector 147 | function collector() external view returns (address); 148 | 149 | /// @notice Returns the end of the bonus period 150 | /// @return Block number of the end of the bonus period 151 | function bonusEndBlock() external view returns (uint256); 152 | 153 | /// @notice Returns the reward awarded per block 154 | /// @return Reward amount per block (with decimals) 155 | function rewardPerBlock() external view returns (uint256); 156 | 157 | /// @notice Returns the bonus multiplier for early stakers 158 | /// @return Multiplier bonus amount 159 | function BONUS_MULTIPLIER() external view returns (uint256); 160 | 161 | /// @notice Returns the info of {poolId} 162 | /// @param poolId Id of the staking pool 163 | /// @return lpToken Address of the PrimitiveManager contract emitting the liquidity pool tokens 164 | /// @return tokenId Id of the PrimitiveManager pool 165 | /// @return allocPoint Allocation points assigned to this pool 166 | /// @return lastRewardBlock Last block number with a reward distribution 167 | /// @return accRewardPerShare Accumulated reward per share with a 1e12 precision 168 | function pools(uint256 poolId) 169 | external 170 | view 171 | returns ( 172 | IERC1155 lpToken, 173 | uint256 tokenId, 174 | uint256 allocPoint, 175 | uint256 lastRewardBlock, 176 | uint256 accRewardPerShare 177 | ); 178 | 179 | /// @notice Returns staking info of {poolId} for {user} 180 | /// @param poolId Id of the staking pool 181 | /// @param user Address of the user 182 | /// @return amount Amount of liquidity pool tokens staked by the user in this pool 183 | /// @return rewardDebt Pending reward for the user for this pool 184 | function users(uint256 poolId, address user) 185 | external 186 | view 187 | returns (uint256 amount, uint256 rewardDebt); 188 | 189 | /// @notice Returns the sum of all allocation points in all pools 190 | /// @return Amount of all allocation points in all poools 191 | function totalAllocPoint() external view returns (uint256); 192 | 193 | /// @notice Returns the starting block of the staking 194 | /// @return Block number of the start of the staking 195 | function startBlock() external view returns (uint256); 196 | 197 | /// @notice Returns the number of pools created 198 | /// @return Number of pools created 199 | function poolLength() external view returns (uint256); 200 | 201 | /// @notice Returns the reward multiplier over the given from and to blocks 202 | /// @return Reward multiplier amount 203 | function getMultiplier(uint256 from, uint256 to) 204 | external 205 | view 206 | returns (uint256); 207 | 208 | /// @notice Returns the pending reward of {user} for the staking pool {pid} 209 | /// @param pid Id of the staking pool 210 | /// @param user Address of the user 211 | /// @return Amount of pending reward 212 | function pendingReward(uint256 pid, address user) 213 | external 214 | view 215 | returns (uint256); 216 | } 217 | -------------------------------------------------------------------------------- /contracts/primitiveChef/PrimitiveChef.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity 0.8.6; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; 6 | import "@openzeppelin/contracts/access/Ownable.sol"; 7 | import "@primitivefi/rmm-manager/contracts/interfaces/IERC1155Permit.sol"; 8 | import "@primitivefi/rmm-manager/contracts/base/Multicall.sol"; 9 | import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; 10 | import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; 11 | import "@primitivefi/rmm-manager/contracts/base/Reentrancy.sol"; 12 | 13 | import "./IPrimitiveChef.sol"; 14 | import "./RewardToken.sol"; 15 | 16 | /// @title PrimitiveChef contract 17 | /// @notice Updated version of SushiSwap MasterChef contract to support Primitive liquidity tokens. 18 | /// Along a couple of improvements, the biggest change is the support of ERC1155 instead of ERC20. 19 | /// @author Primitive 20 | contract PrimitiveChef is 21 | IPrimitiveChef, 22 | Ownable, 23 | ERC1155Holder, 24 | Multicall, 25 | Reentrancy 26 | { 27 | using SafeERC20 for IERC20; 28 | 29 | /// STATE VARIABLES /// 30 | 31 | /// @inheritdoc IPrimitiveChef 32 | RewardToken public override rewardToken; 33 | 34 | /// @inheritdoc IPrimitiveChef 35 | address public override collector; 36 | 37 | /// @inheritdoc IPrimitiveChef 38 | uint256 public override bonusEndBlock; 39 | 40 | /// @inheritdoc IPrimitiveChef 41 | uint256 public override rewardPerBlock; 42 | 43 | /// @inheritdoc IPrimitiveChef 44 | uint256 public constant override BONUS_MULTIPLIER = 10; 45 | 46 | /// @inheritdoc IPrimitiveChef 47 | PoolInfo[] public override pools; 48 | 49 | /// @inheritdoc IPrimitiveChef 50 | mapping(uint256 => mapping(address => UserInfo)) public override users; 51 | 52 | /// @inheritdoc IPrimitiveChef 53 | uint256 public override totalAllocPoint = 0; 54 | 55 | /// @inheritdoc IPrimitiveChef 56 | uint256 public override startBlock; 57 | 58 | /// @dev Null variable to pass with ERC1155 transfer calls 59 | bytes private _data; 60 | 61 | /// EFFECT FUNCTIONS /// 62 | 63 | /// @param rewardToken_ Address of the token rewarded to the stakers 64 | /// @param collector_ Address collecting the staking dev bonus 65 | /// @param rewardPerBlock_ Amount of reward per block 66 | /// @param bonusEndBlock_ Block number of the end of the bonus period 67 | /// @param startBlock_ Block number of the start of the staking 68 | constructor( 69 | RewardToken rewardToken_, 70 | address collector_, 71 | uint256 rewardPerBlock_, 72 | uint256 startBlock_, 73 | uint256 bonusEndBlock_ 74 | ) { 75 | rewardToken = rewardToken_; 76 | collector = collector_; 77 | rewardPerBlock = rewardPerBlock_; 78 | startBlock = startBlock_; 79 | bonusEndBlock = bonusEndBlock_; 80 | } 81 | 82 | /// @inheritdoc IPrimitiveChef 83 | function selfPermit( 84 | address lpToken, 85 | address owner, 86 | bool approved, 87 | uint256 deadline, 88 | uint8 v, 89 | bytes32 r, 90 | bytes32 s 91 | ) external override { 92 | IERC1155Permit(lpToken).permit( 93 | owner, 94 | address(this), 95 | approved, 96 | deadline, 97 | v, 98 | r, 99 | s 100 | ); 101 | } 102 | 103 | /// @inheritdoc IPrimitiveChef 104 | function add( 105 | uint256 allocPoint, 106 | IERC1155 lpToken, 107 | uint256 tokenId, 108 | bool withUpdate 109 | ) external override onlyOwner { 110 | if (withUpdate) massUpdatePools(); 111 | 112 | uint256 lastRewardBlock = block.number > startBlock 113 | ? block.number 114 | : startBlock; 115 | totalAllocPoint += allocPoint; 116 | 117 | pools.push( 118 | PoolInfo({ 119 | lpToken: lpToken, 120 | tokenId: tokenId, 121 | allocPoint: allocPoint, 122 | lastRewardBlock: lastRewardBlock, 123 | accRewardPerShare: 0 124 | }) 125 | ); 126 | } 127 | 128 | /// @inheritdoc IPrimitiveChef 129 | function set( 130 | uint256 pid, 131 | uint256 allocPoint, 132 | bool withUpdate 133 | ) external override onlyOwner { 134 | if (withUpdate) massUpdatePools(); 135 | 136 | totalAllocPoint -= pools[pid].allocPoint + allocPoint; 137 | pools[pid].allocPoint = allocPoint; 138 | } 139 | 140 | /// @inheritdoc IPrimitiveChef 141 | function massUpdatePools() public override { 142 | uint256 length = pools.length; 143 | 144 | for (uint256 pid = 0; pid < length; pid += 1) { 145 | updatePool(pid); 146 | } 147 | } 148 | 149 | /// @inheritdoc IPrimitiveChef 150 | function updatePool(uint256 pid) public override { 151 | PoolInfo storage pool = pools[pid]; 152 | 153 | if (block.number <= pool.lastRewardBlock) return; 154 | 155 | uint256 lpSupply = pool.lpToken.balanceOf(address(this), pool.tokenId); 156 | 157 | if (lpSupply == 0) { 158 | pool.lastRewardBlock = block.number; 159 | return; 160 | } 161 | 162 | uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); 163 | uint256 reward = (multiplier * rewardPerBlock * pool.allocPoint) / 164 | totalAllocPoint; 165 | 166 | rewardToken.mint(collector, reward / 10); 167 | rewardToken.mint(address(this), reward); 168 | 169 | pool.accRewardPerShare += (reward * 1e12) / lpSupply; 170 | pool.lastRewardBlock = block.number; 171 | } 172 | 173 | /// @inheritdoc IPrimitiveChef 174 | function deposit(uint256 pid, uint256 amount) external override lock { 175 | PoolInfo storage pool = pools[pid]; 176 | UserInfo storage user = users[pid][msg.sender]; 177 | 178 | updatePool(pid); 179 | 180 | if (user.amount > 0) { 181 | uint256 pending = (user.amount * pool.accRewardPerShare) / 182 | 1e12 - 183 | user.rewardDebt; 184 | safeRewardTransfer(msg.sender, pending); 185 | } 186 | 187 | pool.lpToken.safeTransferFrom( 188 | msg.sender, 189 | address(this), 190 | pool.tokenId, 191 | amount, 192 | _data 193 | ); 194 | 195 | user.amount += amount; 196 | user.rewardDebt = (user.amount * pool.accRewardPerShare) / 1e12; 197 | 198 | emit Deposit(msg.sender, pid, amount); 199 | } 200 | 201 | /// @inheritdoc IPrimitiveChef 202 | function withdraw(uint256 pid, uint256 amount) external override lock { 203 | PoolInfo storage pool = pools[pid]; 204 | UserInfo storage user = users[pid][msg.sender]; 205 | 206 | if (amount > user.amount) revert WithdrawAmountError(); 207 | 208 | updatePool(pid); 209 | 210 | uint256 pending = (user.amount * pool.accRewardPerShare) / 211 | 1e12 - 212 | user.rewardDebt; 213 | 214 | safeRewardTransfer(msg.sender, pending); 215 | 216 | user.amount -= amount; 217 | user.rewardDebt = (user.amount * pool.accRewardPerShare) / 1e12; 218 | 219 | pool.lpToken.safeTransferFrom( 220 | address(this), 221 | msg.sender, 222 | pool.tokenId, 223 | amount, 224 | _data 225 | ); 226 | 227 | emit Withdraw(msg.sender, pid, amount); 228 | } 229 | 230 | /// @inheritdoc IPrimitiveChef 231 | function emergencyWithdraw(uint256 pid) external override lock { 232 | PoolInfo storage pool = pools[pid]; 233 | UserInfo storage user = users[pid][msg.sender]; 234 | 235 | pool.lpToken.safeTransferFrom( 236 | address(this), 237 | msg.sender, 238 | pool.tokenId, 239 | user.amount, 240 | _data 241 | ); 242 | 243 | emit EmergencyWithdraw(msg.sender, pid, user.amount); 244 | 245 | user.amount = 0; 246 | user.rewardDebt = 0; 247 | } 248 | 249 | /// @inheritdoc IPrimitiveChef 250 | function setCollector(address newCollector) external override onlyOwner { 251 | collector = newCollector; 252 | } 253 | 254 | /// VIEW FUNCTIONS /// 255 | 256 | /// @inheritdoc IPrimitiveChef 257 | function poolLength() external view override returns (uint256) { 258 | return pools.length; 259 | } 260 | 261 | /// @inheritdoc IPrimitiveChef 262 | function getMultiplier(uint256 from, uint256 to) 263 | public 264 | view 265 | override 266 | returns (uint256) 267 | { 268 | if (to <= bonusEndBlock) return to - from * BONUS_MULTIPLIER; 269 | if (from >= bonusEndBlock) return to - from; 270 | return bonusEndBlock - from * BONUS_MULTIPLIER + to - bonusEndBlock; 271 | } 272 | 273 | /// @inheritdoc IPrimitiveChef 274 | function pendingReward(uint256 pid, address account) 275 | external 276 | view 277 | override 278 | returns (uint256) 279 | { 280 | PoolInfo storage pool = pools[pid]; 281 | UserInfo storage user = users[pid][account]; 282 | 283 | uint256 accRewardPerShare = pool.accRewardPerShare; 284 | uint256 lpSupply = pool.lpToken.balanceOf(address(this), pool.tokenId); 285 | 286 | if (block.number > pool.lastRewardBlock && lpSupply != 0) { 287 | uint256 multiplier = getMultiplier( 288 | pool.lastRewardBlock, 289 | block.number 290 | ); 291 | uint256 sushiReward = (multiplier * 292 | rewardPerBlock * 293 | pool.allocPoint) / totalAllocPoint; 294 | accRewardPerShare += (sushiReward * 1e12) / lpSupply; 295 | } 296 | 297 | return (user.amount * accRewardPerShare) / 1e12 - user.rewardDebt; 298 | } 299 | 300 | /// INTERNAL FUNCTIONS /// 301 | 302 | // Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough SUSHIs. 303 | function safeRewardTransfer(address to, uint256 amount) internal { 304 | uint256 balance = rewardToken.balanceOf(address(this)); 305 | 306 | if (amount > balance) { 307 | rewardToken.transfer(to, balance); 308 | } else { 309 | rewardToken.transfer(to, amount); 310 | } 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /contracts/test/WETH9.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-only 2 | 3 | // Copyright (C) 2015, 2016, 2017 Dapphub 4 | 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | pragma solidity 0.8.9; 19 | 20 | contract WETH9 { 21 | string public name = "Wrapped Ether"; 22 | string public symbol = "WETH"; 23 | uint8 public decimals = 18; 24 | 25 | event Approval(address indexed src, address indexed guy, uint256 wad); 26 | event Transfer(address indexed src, address indexed dst, uint256 wad); 27 | event Deposit(address indexed dst, uint256 wad); 28 | event Withdrawal(address indexed src, uint256 wad); 29 | 30 | mapping(address => uint256) public balanceOf; 31 | mapping(address => mapping(address => uint256)) public allowance; 32 | 33 | function sendETH(address recipient) public payable { 34 | payable(recipient).transfer(msg.value); 35 | } 36 | 37 | function deposit() public payable { 38 | balanceOf[msg.sender] += msg.value; 39 | emit Deposit(msg.sender, msg.value); 40 | } 41 | 42 | function withdraw(uint256 wad) public { 43 | require(balanceOf[msg.sender] >= wad); 44 | balanceOf[msg.sender] -= wad; 45 | payable(msg.sender).transfer(wad); 46 | emit Withdrawal(msg.sender, wad); 47 | } 48 | 49 | function totalSupply() public view returns (uint256) { 50 | return address(this).balance; 51 | } 52 | 53 | function approve(address guy, uint256 wad) public returns (bool) { 54 | allowance[msg.sender][guy] = wad; 55 | emit Approval(msg.sender, guy, wad); 56 | return true; 57 | } 58 | 59 | function transfer(address dst, uint256 wad) public returns (bool) { 60 | return transferFrom(msg.sender, dst, wad); 61 | } 62 | 63 | function transferFrom( 64 | address src, 65 | address dst, 66 | uint256 wad 67 | ) public returns (bool) { 68 | require(balanceOf[src] >= wad); 69 | 70 | if ( 71 | src != msg.sender && allowance[src][msg.sender] != type(uint256).max 72 | ) { 73 | require(allowance[src][msg.sender] >= wad); 74 | allowance[src][msg.sender] -= wad; 75 | } 76 | 77 | balanceOf[src] -= wad; 78 | balanceOf[dst] += wad; 79 | 80 | emit Transfer(src, dst, wad); 81 | 82 | return true; 83 | } 84 | } 85 | 86 | /* 87 | GNU GENERAL PUBLIC LICENSE 88 | Version 3, 29 June 2007 89 | 90 | Copyright (C) 2007 Free Software Foundation, Inc. 91 | Everyone is permitted to copy and distribute verbatim copies 92 | of this license document, but changing it is not allowed. 93 | 94 | Preamble 95 | 96 | The GNU General Public License is a free, copyleft license for 97 | software and other kinds of works. 98 | 99 | The licenses for most software and other practical works are designed 100 | to take away your freedom to share and change the works. By contrast, 101 | the GNU General Public License is intended to guarantee your freedom to 102 | share and change all versions of a program--to make sure it remains free 103 | software for all its users. We, the Free Software Foundation, use the 104 | GNU General Public License for most of our software; it applies also to 105 | any other work released this way by its authors. You can apply it to 106 | your programs, too. 107 | 108 | When we speak of free software, we are referring to freedom, not 109 | price. Our General Public Licenses are designed to make sure that you 110 | have the freedom to distribute copies of free software (and charge for 111 | them if you wish), that you receive source code or can get it if you 112 | want it, that you can change the software or use pieces of it in new 113 | free programs, and that you know you can do these things. 114 | 115 | To protect your rights, we need to prevent others from denying you 116 | these rights or asking you to surrender the rights. Therefore, you have 117 | certain responsibilities if you distribute copies of the software, or if 118 | you modify it: responsibilities to respect the freedom of others. 119 | 120 | For example, if you distribute copies of such a program, whether 121 | gratis or for a fee, you must pass on to the recipients the same 122 | freedoms that you received. You must make sure that they, too, receive 123 | or can get the source code. And you must show them these terms so they 124 | know their rights. 125 | 126 | Developers that use the GNU GPL protect your rights with two steps: 127 | (1) assert copyright on the software, and (2) offer you this License 128 | giving you legal permission to copy, distribute and/or modify it. 129 | 130 | For the developers' and authors' protection, the GPL clearly explains 131 | that there is no warranty for this free software. For both users' and 132 | authors' sake, the GPL requires that modified versions be marked as 133 | changed, so that their problems will not be attributed erroneously to 134 | authors of previous versions. 135 | 136 | Some devices are designed to deny users access to install or run 137 | modified versions of the software inside them, although the manufacturer 138 | can do so. This is fundamentally incompatible with the aim of 139 | protecting users' freedom to change the software. The systematic 140 | pattern of such abuse occurs in the area of products for individuals to 141 | use, which is precisely where it is most unacceptable. Therefore, we 142 | have designed this version of the GPL to prohibit the practice for those 143 | products. If such problems arise substantially in other domains, we 144 | stand ready to extend this provision to those domains in future versions 145 | of the GPL, as needed to protect the freedom of users. 146 | 147 | Finally, every program is threatened constantly by software patents. 148 | States should not allow patents to restrict development and use of 149 | software on general-purpose computers, but in those that do, we wish to 150 | avoid the special danger that patents applied to a free program could 151 | make it effectively proprietary. To prevent this, the GPL assures that 152 | patents cannot be used to render the program non-free. 153 | 154 | The precise terms and conditions for copying, distribution and 155 | modification follow. 156 | 157 | TERMS AND CONDITIONS 158 | 159 | 0. Definitions. 160 | 161 | "This License" refers to version 3 of the GNU General Public License. 162 | 163 | "Copyright" also means copyright-like laws that apply to other kinds of 164 | works, such as semiconductor masks. 165 | 166 | "The Program" refers to any copyrightable work licensed under this 167 | License. Each licensee is addressed as "you". "Licensees" and 168 | "recipients" may be individuals or organizations. 169 | 170 | To "modify" a work means to copy from or adapt all or part of the work 171 | in a fashion requiring copyright permission, other than the making of an 172 | exact copy. The resulting work is called a "modified version" of the 173 | earlier work or a work "based on" the earlier work. 174 | 175 | A "covered work" means either the unmodified Program or a work based 176 | on the Program. 177 | 178 | To "propagate" a work means to do anything with it that, without 179 | permission, would make you directly or secondarily liable for 180 | infringement under applicable copyright law, except executing it on a 181 | computer or modifying a private copy. Propagation includes copying, 182 | distribution (with or without modification), making available to the 183 | public, and in some countries other activities as well. 184 | 185 | To "convey" a work means any kind of propagation that enables other 186 | parties to make or receive copies. Mere interaction with a user through 187 | a computer network, with no transfer of a copy, is not conveying. 188 | 189 | An interactive user interface displays "Appropriate Legal Notices" 190 | to the extent that it includes a convenient and prominently visible 191 | feature that (1) displays an appropriate copyright notice, and (2) 192 | tells the user that there is no warranty for the work (except to the 193 | extent that warranties are provided), that licensees may convey the 194 | work under this License, and how to view a copy of this License. If 195 | the interface presents a list of user commands or options, such as a 196 | menu, a prominent item in the list meets this criterion. 197 | 198 | 1. Source Code. 199 | 200 | The "source code" for a work means the preferred form of the work 201 | for making modifications to it. "Object code" means any non-source 202 | form of a work. 203 | 204 | A "Standard Interface" means an interface that either is an official 205 | standard defined by a recognized standards body, or, in the case of 206 | interfaces specified for a particular programming language, one that 207 | is widely used among developers working in that language. 208 | 209 | The "System Libraries" of an executable work include anything, other 210 | than the work as a whole, that (a) is included in the normal form of 211 | packaging a Major Component, but which is not part of that Major 212 | Component, and (b) serves only to enable use of the work with that 213 | Major Component, or to implement a Standard Interface for which an 214 | implementation is available to the public in source code form. A 215 | "Major Component", in this context, means a major essential component 216 | (kernel, window system, and so on) of the specific operating system 217 | (if any) on which the executable work runs, or a compiler used to 218 | produce the work, or an object code interpreter used to run it. 219 | 220 | The "Corresponding Source" for a work in object code form means all 221 | the source code needed to generate, install, and (for an executable 222 | work) run the object code and to modify the work, including scripts to 223 | control those activities. However, it does not include the work's 224 | System Libraries, or general-purpose tools or generally available free 225 | programs which are used unmodified in performing those activities but 226 | which are not part of the work. For example, Corresponding Source 227 | includes interface definition files associated with source files for 228 | the work, and the source code for shared libraries and dynamically 229 | linked subprograms that the work is specifically designed to require, 230 | such as by intimate data communication or control flow between those 231 | subprograms and other parts of the work. 232 | 233 | The Corresponding Source need not include anything that users 234 | can regenerate automatically from other parts of the Corresponding 235 | Source. 236 | 237 | The Corresponding Source for a work in source code form is that 238 | same work. 239 | 240 | 2. Basic Permissions. 241 | 242 | All rights granted under this License are granted for the term of 243 | copyright on the Program, and are irrevocable provided the stated 244 | conditions are met. This License explicitly affirms your unlimited 245 | permission to run the unmodified Program. The output from running a 246 | covered work is covered by this License only if the output, given its 247 | content, constitutes a covered work. This License acknowledges your 248 | rights of fair use or other equivalent, as provided by copyright law. 249 | 250 | You may make, run and propagate covered works that you do not 251 | convey, without conditions so long as your license otherwise remains 252 | in force. You may convey covered works to others for the sole purpose 253 | of having them make modifications exclusively for you, or provide you 254 | with facilities for running those works, provided that you comply with 255 | the terms of this License in conveying all material for which you do 256 | not control copyright. Those thus making or running the covered works 257 | for you must do so exclusively on your behalf, under your direction 258 | and control, on terms that prohibit them from making any copies of 259 | your copyrighted material outside their relationship with you. 260 | 261 | Conveying under any other circumstances is permitted solely under 262 | the conditions stated below. Sublicensing is not allowed; section 10 263 | makes it unnecessary. 264 | 265 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 266 | 267 | No covered work shall be deemed part of an effective technological 268 | measure under any applicable law fulfilling obligations under article 269 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 270 | similar laws prohibiting or restricting circumvention of such 271 | measures. 272 | 273 | When you convey a covered work, you waive any legal power to forbid 274 | circumvention of technological measures to the extent such circumvention 275 | is effected by exercising rights under this License with respect to 276 | the covered work, and you disclaim any intention to limit operation or 277 | modification of the work as a means of enforcing, against the work's 278 | users, your or third parties' legal rights to forbid circumvention of 279 | technological measures. 280 | 281 | 4. Conveying Verbatim Copies. 282 | 283 | You may convey verbatim copies of the Program's source code as you 284 | receive it, in any medium, provided that you conspicuously and 285 | appropriately publish on each copy an appropriate copyright notice; 286 | keep intact all notices stating that this License and any 287 | non-permissive terms added in accord with section 7 apply to the code; 288 | keep intact all notices of the absence of any warranty; and give all 289 | recipients a copy of this License along with the Program. 290 | 291 | You may charge any price or no price for each copy that you convey, 292 | and you may offer support or warranty protection for a fee. 293 | 294 | 5. Conveying Modified Source Versions. 295 | 296 | You may convey a work based on the Program, or the modifications to 297 | produce it from the Program, in the form of source code under the 298 | terms of section 4, provided that you also meet all of these conditions: 299 | 300 | a) The work must carry prominent notices stating that you modified 301 | it, and giving a relevant date. 302 | 303 | b) The work must carry prominent notices stating that it is 304 | released under this License and any conditions added under section 305 | 7. This requirement modifies the requirement in section 4 to 306 | "keep intact all notices". 307 | 308 | c) You must license the entire work, as a whole, under this 309 | License to anyone who comes into possession of a copy. This 310 | License will therefore apply, along with any applicable section 7 311 | additional terms, to the whole of the work, and all its parts, 312 | regardless of how they are packaged. This License gives no 313 | permission to license the work in any other way, but it does not 314 | invalidate such permission if you have separately received it. 315 | 316 | d) If the work has interactive user interfaces, each must display 317 | Appropriate Legal Notices; however, if the Program has interactive 318 | interfaces that do not display Appropriate Legal Notices, your 319 | work need not make them do so. 320 | 321 | A compilation of a covered work with other separate and independent 322 | works, which are not by their nature extensions of the covered work, 323 | and which are not combined with it such as to form a larger program, 324 | in or on a volume of a storage or distribution medium, is called an 325 | "aggregate" if the compilation and its resulting copyright are not 326 | used to limit the access or legal rights of the compilation's users 327 | beyond what the individual works permit. Inclusion of a covered work 328 | in an aggregate does not cause this License to apply to the other 329 | parts of the aggregate. 330 | 331 | 6. Conveying Non-Source Forms. 332 | 333 | You may convey a covered work in object code form under the terms 334 | of sections 4 and 5, provided that you also convey the 335 | machine-readable Corresponding Source under the terms of this License, 336 | in one of these ways: 337 | 338 | a) Convey the object code in, or embodied in, a physical product 339 | (including a physical distribution medium), accompanied by the 340 | Corresponding Source fixed on a durable physical medium 341 | customarily used for software interchange. 342 | 343 | b) Convey the object code in, or embodied in, a physical product 344 | (including a physical distribution medium), accompanied by a 345 | written offer, valid for at least three years and valid for as 346 | long as you offer spare parts or customer support for that product 347 | model, to give anyone who possesses the object code either (1) a 348 | copy of the Corresponding Source for all the software in the 349 | product that is covered by this License, on a durable physical 350 | medium customarily used for software interchange, for a price no 351 | more than your reasonable cost of physically performing this 352 | conveying of source, or (2) access to copy the 353 | Corresponding Source from a network server at no charge. 354 | 355 | c) Convey individual copies of the object code with a copy of the 356 | written offer to provide the Corresponding Source. This 357 | alternative is allowed only occasionally and noncommercially, and 358 | only if you received the object code with such an offer, in accord 359 | with subsection 6b. 360 | 361 | d) Convey the object code by offering access from a designated 362 | place (gratis or for a charge), and offer equivalent access to the 363 | Corresponding Source in the same way through the same place at no 364 | further charge. You need not require recipients to copy the 365 | Corresponding Source along with the object code. If the place to 366 | copy the object code is a network server, the Corresponding Source 367 | may be on a different server (operated by you or a third party) 368 | that supports equivalent copying facilities, provided you maintain 369 | clear directions next to the object code saying where to find the 370 | Corresponding Source. Regardless of what server hosts the 371 | Corresponding Source, you remain obligated to ensure that it is 372 | available for as long as needed to satisfy these requirements. 373 | 374 | e) Convey the object code using peer-to-peer transmission, provided 375 | you inform other peers where the object code and Corresponding 376 | Source of the work are being offered to the general public at no 377 | charge under subsection 6d. 378 | 379 | A separable portion of the object code, whose source code is excluded 380 | from the Corresponding Source as a System Library, need not be 381 | included in conveying the object code work. 382 | 383 | A "User Product" is either (1) a "consumer product", which means any 384 | tangible personal property which is normally used for personal, family, 385 | or household purposes, or (2) anything designed or sold for incorporation 386 | into a dwelling. In determining whether a product is a consumer product, 387 | doubtful cases shall be resolved in favor of coverage. For a particular 388 | product received by a particular user, "normally used" refers to a 389 | typical or common use of that class of product, regardless of the status 390 | of the particular user or of the way in which the particular user 391 | actually uses, or expects or is expected to use, the product. A product 392 | is a consumer product regardless of whether the product has substantial 393 | commercial, industrial or non-consumer uses, unless such uses represent 394 | the only significant mode of use of the product. 395 | 396 | "Installation Information" for a User Product means any methods, 397 | procedures, authorization keys, or other information required to install 398 | and execute modified versions of a covered work in that User Product from 399 | a modified version of its Corresponding Source. The information must 400 | suffice to ensure that the continued functioning of the modified object 401 | code is in no case prevented or interfered with solely because 402 | modification has been made. 403 | 404 | If you convey an object code work under this section in, or with, or 405 | specifically for use in, a User Product, and the conveying occurs as 406 | part of a transaction in which the right of possession and use of the 407 | User Product is transferred to the recipient in perpetuity or for a 408 | fixed term (regardless of how the transaction is characterized), the 409 | Corresponding Source conveyed under this section must be accompanied 410 | by the Installation Information. But this requirement does not apply 411 | if neither you nor any third party retains the ability to install 412 | modified object code on the User Product (for example, the work has 413 | been installed in ROM). 414 | 415 | The requirement to provide Installation Information does not include a 416 | requirement to continue to provide support service, warranty, or updates 417 | for a work that has been modified or installed by the recipient, or for 418 | the User Product in which it has been modified or installed. Access to a 419 | network may be denied when the modification itself materially and 420 | adversely affects the operation of the network or violates the rules and 421 | protocols for communication across the network. 422 | 423 | Corresponding Source conveyed, and Installation Information provided, 424 | in accord with this section must be in a format that is publicly 425 | documented (and with an implementation available to the public in 426 | source code form), and must require no special password or key for 427 | unpacking, reading or copying. 428 | 429 | 7. Additional Terms. 430 | 431 | "Additional permissions" are terms that supplement the terms of this 432 | License by making exceptions from one or more of its conditions. 433 | Additional permissions that are applicable to the entire Program shall 434 | be treated as though they were included in this License, to the extent 435 | that they are valid under applicable law. If additional permissions 436 | apply only to part of the Program, that part may be used separately 437 | under those permissions, but the entire Program remains governed by 438 | this License without regard to the additional permissions. 439 | 440 | When you convey a copy of a covered work, you may at your option 441 | remove any additional permissions from that copy, or from any part of 442 | it. (Additional permissions may be written to require their own 443 | removal in certain cases when you modify the work.) You may place 444 | additional permissions on material, added by you to a covered work, 445 | for which you have or can give appropriate copyright permission. 446 | 447 | Notwithstanding any other provision of this License, for material you 448 | add to a covered work, you may (if authorized by the copyright holders of 449 | that material) supplement the terms of this License with terms: 450 | 451 | a) Disclaiming warranty or limiting liability differently from the 452 | terms of sections 15 and 16 of this License; or 453 | 454 | b) Requiring preservation of specified reasonable legal notices or 455 | author attributions in that material or in the Appropriate Legal 456 | Notices displayed by works containing it; or 457 | 458 | c) Prohibiting misrepresentation of the origin of that material, or 459 | requiring that modified versions of such material be marked in 460 | reasonable ways as different from the original version; or 461 | 462 | d) Limiting the use for publicity purposes of names of licensors or 463 | authors of the material; or 464 | 465 | e) Declining to grant rights under trademark law for use of some 466 | trade names, trademarks, or service marks; or 467 | 468 | f) Requiring indemnification of licensors and authors of that 469 | material by anyone who conveys the material (or modified versions of 470 | it) with contractual assumptions of liability to the recipient, for 471 | any liability that these contractual assumptions directly impose on 472 | those licensors and authors. 473 | 474 | All other non-permissive additional terms are considered "further 475 | restrictions" within the meaning of section 10. If the Program as you 476 | received it, or any part of it, contains a notice stating that it is 477 | governed by this License along with a term that is a further 478 | restriction, you may remove that term. If a license document contains 479 | a further restriction but permits relicensing or conveying under this 480 | License, you may add to a covered work material governed by the terms 481 | of that license document, provided that the further restriction does 482 | not survive such relicensing or conveying. 483 | 484 | If you add terms to a covered work in accord with this section, you 485 | must place, in the relevant source files, a statement of the 486 | additional terms that apply to those files, or a notice indicating 487 | where to find the applicable terms. 488 | 489 | Additional terms, permissive or non-permissive, may be stated in the 490 | form of a separately written license, or stated as exceptions; 491 | the above requirements apply either way. 492 | 493 | 8. Termination. 494 | 495 | You may not propagate or modify a covered work except as expressly 496 | provided under this License. Any attempt otherwise to propagate or 497 | modify it is void, and will automatically terminate your rights under 498 | this License (including any patent licenses granted under the third 499 | paragraph of section 11). 500 | 501 | However, if you cease all violation of this License, then your 502 | license from a particular copyright holder is reinstated (a) 503 | provisionally, unless and until the copyright holder explicitly and 504 | finally terminates your license, and (b) permanently, if the copyright 505 | holder fails to notify you of the violation by some reasonable means 506 | prior to 60 days after the cessation. 507 | 508 | Moreover, your license from a particular copyright holder is 509 | reinstated permanently if the copyright holder notifies you of the 510 | violation by some reasonable means, this is the first time you have 511 | received notice of violation of this License (for any work) from that 512 | copyright holder, and you cure the violation prior to 30 days after 513 | your receipt of the notice. 514 | 515 | Termination of your rights under this section does not terminate the 516 | licenses of parties who have received copies or rights from you under 517 | this License. If your rights have been terminated and not permanently 518 | reinstated, you do not qualify to receive new licenses for the same 519 | material under section 10. 520 | 521 | 9. Acceptance Not Required for Having Copies. 522 | 523 | You are not required to accept this License in order to receive or 524 | run a copy of the Program. Ancillary propagation of a covered work 525 | occurring solely as a consequence of using peer-to-peer transmission 526 | to receive a copy likewise does not require acceptance. However, 527 | nothing other than this License grants you permission to propagate or 528 | modify any covered work. These actions infringe copyright if you do 529 | not accept this License. Therefore, by modifying or propagating a 530 | covered work, you indicate your acceptance of this License to do so. 531 | 532 | 10. Automatic Licensing of Downstream Recipients. 533 | 534 | Each time you convey a covered work, the recipient automatically 535 | receives a license from the original licensors, to run, modify and 536 | propagate that work, subject to this License. You are not responsible 537 | for enforcing compliance by third parties with this License. 538 | 539 | An "entity transaction" is a transaction transferring control of an 540 | organization, or substantially all assets of one, or subdividing an 541 | organization, or merging organizations. If propagation of a covered 542 | work results from an entity transaction, each party to that 543 | transaction who receives a copy of the work also receives whatever 544 | licenses to the work the party's predecessor in interest had or could 545 | give under the previous paragraph, plus a right to possession of the 546 | Corresponding Source of the work from the predecessor in interest, if 547 | the predecessor has it or can get it with reasonable efforts. 548 | 549 | You may not impose any further restrictions on the exercise of the 550 | rights granted or affirmed under this License. For example, you may 551 | not impose a license fee, royalty, or other charge for exercise of 552 | rights granted under this License, and you may not initiate litigation 553 | (including a cross-claim or counterclaim in a lawsuit) alleging that 554 | any patent claim is infringed by making, using, selling, offering for 555 | sale, or importing the Program or any portion of it. 556 | 557 | 11. Patents. 558 | 559 | A "contributor" is a copyright holder who authorizes use under this 560 | License of the Program or a work on which the Program is based. The 561 | work thus licensed is called the contributor's "contributor version". 562 | 563 | A contributor's "essential patent claims" are all patent claims 564 | owned or controlled by the contributor, whether already acquired or 565 | hereafter acquired, that would be infringed by some manner, permitted 566 | by this License, of making, using, or selling its contributor version, 567 | but do not include claims that would be infringed only as a 568 | consequence of further modification of the contributor version. For 569 | purposes of this definition, "control" includes the right to grant 570 | patent sublicenses in a manner consistent with the requirements of 571 | this License. 572 | 573 | Each contributor grants you a non-exclusive, worldwide, royalty-free 574 | patent license under the contributor's essential patent claims, to 575 | make, use, sell, offer for sale, import and otherwise run, modify and 576 | propagate the contents of its contributor version. 577 | 578 | In the following three paragraphs, a "patent license" is any express 579 | agreement or commitment, however denominated, not to enforce a patent 580 | (such as an express permission to practice a patent or covenant not to 581 | sue for patent infringement). To "grant" such a patent license to a 582 | party means to make such an agreement or commitment not to enforce a 583 | patent against the party. 584 | 585 | If you convey a covered work, knowingly relying on a patent license, 586 | and the Corresponding Source of the work is not available for anyone 587 | to copy, free of charge and under the terms of this License, through a 588 | publicly available network server or other readily accessible means, 589 | then you must either (1) cause the Corresponding Source to be so 590 | available, or (2) arrange to deprive yourself of the benefit of the 591 | patent license for this particular work, or (3) arrange, in a manner 592 | consistent with the requirements of this License, to extend the patent 593 | license to downstream recipients. "Knowingly relying" means you have 594 | actual knowledge that, but for the patent license, your conveying the 595 | covered work in a country, or your recipient's use of the covered work 596 | in a country, would infringe one or more identifiable patents in that 597 | country that you have reason to believe are valid. 598 | 599 | If, pursuant to or in connection with a single transaction or 600 | arrangement, you convey, or propagate by procuring conveyance of, a 601 | covered work, and grant a patent license to some of the parties 602 | receiving the covered work authorizing them to use, propagate, modify 603 | or convey a specific copy of the covered work, then the patent license 604 | you grant is automatically extended to all recipients of the covered 605 | work and works based on it. 606 | 607 | A patent license is "discriminatory" if it does not include within 608 | the scope of its coverage, prohibits the exercise of, or is 609 | conditioned on the non-exercise of one or more of the rights that are 610 | specifically granted under this License. You may not convey a covered 611 | work if you are a party to an arrangement with a third party that is 612 | in the business of distributing software, under which you make payment 613 | to the third party based on the extent of your activity of conveying 614 | the work, and under which the third party grants, to any of the 615 | parties who would receive the covered work from you, a discriminatory 616 | patent license (a) in connection with copies of the covered work 617 | conveyed by you (or copies made from those copies), or (b) primarily 618 | for and in connection with specific products or compilations that 619 | contain the covered work, unless you entered into that arrangement, 620 | or that patent license was granted, prior to 28 March 2007. 621 | 622 | Nothing in this License shall be construed as excluding or limiting 623 | any implied license or other defenses to infringement that may 624 | otherwise be available to you under applicable patent law. 625 | 626 | 12. No Surrender of Others' Freedom. 627 | 628 | If conditions are imposed on you (whether by court order, agreement or 629 | otherwise) that contradict the conditions of this License, they do not 630 | excuse you from the conditions of this License. If you cannot convey a 631 | covered work so as to satisfy simultaneously your obligations under this 632 | License and any other pertinent obligations, then as a consequence you may 633 | not convey it at all. For example, if you agree to terms that obligate you 634 | to collect a royalty for further conveying from those to whom you convey 635 | the Program, the only way you could satisfy both those terms and this 636 | License would be to refrain entirely from conveying the Program. 637 | 638 | 13. Use with the GNU Affero General Public License. 639 | 640 | Notwithstanding any other provision of this License, you have 641 | permission to link or combine any covered work with a work licensed 642 | under version 3 of the GNU Affero General Public License into a single 643 | combined work, and to convey the resulting work. The terms of this 644 | License will continue to apply to the part which is the covered work, 645 | but the special requirements of the GNU Affero General Public License, 646 | section 13, concerning interaction through a network will apply to the 647 | combination as such. 648 | 649 | 14. Revised Versions of this License. 650 | 651 | The Free Software Foundation may publish revised and/or new versions of 652 | the GNU General Public License from time to time. Such new versions will 653 | be similar in spirit to the present version, but may differ in detail to 654 | address new problems or concerns. 655 | 656 | Each version is given a distinguishing version number. If the 657 | Program specifies that a certain numbered version of the GNU General 658 | Public License "or any later version" applies to it, you have the 659 | option of following the terms and conditions either of that numbered 660 | version or of any later version published by the Free Software 661 | Foundation. If the Program does not specify a version number of the 662 | GNU General Public License, you may choose any version ever published 663 | by the Free Software Foundation. 664 | 665 | If the Program specifies that a proxy can decide which future 666 | versions of the GNU General Public License can be used, that proxy's 667 | public statement of acceptance of a version permanently authorizes you 668 | to choose that version for the Program. 669 | 670 | Later license versions may give you additional or different 671 | permissions. However, no additional obligations are imposed on any 672 | author or copyright holder as a result of your choosing to follow a 673 | later version. 674 | 675 | 15. Disclaimer of Warranty. 676 | 677 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 678 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 679 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 680 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 681 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 682 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 683 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 684 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 685 | 686 | 16. Limitation of Liability. 687 | 688 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 689 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 690 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 691 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 692 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 693 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 694 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 695 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 696 | SUCH DAMAGES. 697 | 698 | 17. Interpretation of Sections 15 and 16. 699 | 700 | If the disclaimer of warranty and limitation of liability provided 701 | above cannot be given local legal effect according to their terms, 702 | reviewing courts shall apply local law that most closely approximates 703 | an absolute waiver of all civil liability in connection with the 704 | Program, unless a warranty or assumption of liability accompanies a 705 | copy of the Program in return for a fee. 706 | 707 | END OF TERMS AND CONDITIONS 708 | 709 | How to Apply These Terms to Your New Programs 710 | 711 | If you develop a new program, and you want it to be of the greatest 712 | possible use to the public, the best way to achieve this is to make it 713 | free software which everyone can redistribute and change under these terms. 714 | 715 | To do so, attach the following notices to the program. It is safest 716 | to attach them to the start of each source file to most effectively 717 | state the exclusion of warranty; and each file should have at least 718 | the "copyright" line and a pointer to where the full notice is found. 719 | 720 | 721 | Copyright (C) 722 | 723 | This program is free software: you can redistribute it and/or modify 724 | it under the terms of the GNU General Public License as published by 725 | the Free Software Foundation, either version 3 of the License, or 726 | (at your option) any later version. 727 | 728 | This program is distributed in the hope that it will be useful, 729 | but WITHOUT ANY WARRANTY; without even the implied warranty of 730 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 731 | GNU General Public License for more details. 732 | 733 | You should have received a copy of the GNU General Public License 734 | along with this program. If not, see . 735 | 736 | Also add information on how to contact you by electronic and paper mail. 737 | 738 | If the program does terminal interaction, make it output a short 739 | notice like this when it starts in an interactive mode: 740 | 741 | Copyright (C) 742 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 743 | This is free software, and you are welcome to redistribute it 744 | under certain conditions; type `show c' for details. 745 | 746 | The hypothetical commands `show w' and `show c' should show the appropriate 747 | parts of the General Public License. Of course, your program's commands 748 | might be different; for a GUI interface, you would use an "about box". 749 | 750 | You should also get your employer (if you work as a programmer) or school, 751 | if any, to sign a "copyright disclaimer" for the program, if necessary. 752 | For more information on this, and how to apply and follow the GNU GPL, see 753 | . 754 | 755 | The GNU General Public License does not permit incorporating your program 756 | into proprietary programs. If your program is a subroutine library, you 757 | may consider it more useful to permit linking proprietary applications with 758 | the library. If this is what you want to do, use the GNU Lesser General 759 | Public License instead of this License. But first, please read 760 | . 761 | 762 | */ 763 | --------------------------------------------------------------------------------