├── .vscode └── settings.json ├── .prettierignore ├── .gitignore ├── .prettierrc ├── remappings.txt ├── .env.example ├── .gitmodules ├── src ├── interfaces │ ├── IERC165.sol │ ├── IERC20.sol │ └── IERC721.sol ├── test │ ├── utils │ │ └── DSTestPlus.sol │ ├── TwamFactory.t.sol │ └── TwamBase.t.sol ├── TwamFactory.sol └── TwamBase.sol ├── .github └── workflows │ ├── tests.yml │ └── lints.yml ├── .solhint.json ├── .dapprc ├── package.json ├── Makefile ├── README.md └── LICENSE /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "makefile.extensionOutputFolder": "./.vscode" 3 | } -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | build 2 | coverage 3 | out 4 | lib 5 | assets 6 | node_modules 7 | .next -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | cache/ 2 | out/ 3 | node_modules/* 4 | node_modules 5 | .env 6 | .env.prod 7 | .vscode/*.log -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "es5", 3 | "tabWidth": 4, 4 | "semi": false, 5 | "singleQuote": false 6 | } -------------------------------------------------------------------------------- /remappings.txt: -------------------------------------------------------------------------------- 1 | @ds=lib/ds-test/src/ 2 | @solmate=lib/solmate/src/ 3 | @std=lib/forge-std/src/ 4 | @clones=lib/clones-with-immutable-args/src/ -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | ## Etherscan API Key ## 2 | ## Used for verification of contracts on deployement ## 3 | ETHERSCAN_API_KEY= 4 | 5 | ## Alchemy API Key ## 6 | ## For deployment ## 7 | ALCHEMY_API_KEY= 8 | 9 | ## Alchmey API Key URL ## 10 | ETH_RPC_URL= 11 | 12 | ## EOA Contract Deployer ## 13 | ETH_FROM= 14 | 15 | ## Block gas limit (max: 15M ie 15000000) ## 16 | ETH_GAS=15000000 17 | 18 | ## Solidity Compiler Version ## 19 | SOLC_VERSION=0.8.11 -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/ds-test"] 2 | path = lib/ds-test 3 | url = https://github.com/dapphub/ds-test 4 | [submodule "lib/solmate"] 5 | path = lib/solmate 6 | url = https://github.com/rari-capital/solmate 7 | [submodule "lib/forge-std"] 8 | path = lib/forge-std 9 | url = https://github.com/brockelmore/forge-std 10 | [submodule "lib/clones-with-immutable-args"] 11 | path = lib/clones-with-immutable-args 12 | url = https://github.com/ZeframLou/clones-with-immutable-args 13 | -------------------------------------------------------------------------------- /src/interfaces/IERC165.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | /// @title ERC165 Interface 5 | /// @dev https://eips.ethereum.org/EIPS/eip-165 6 | /// @author Andreas Bigger 7 | interface IERC165 { 8 | /// @dev Returns if the contract implements the defined interface 9 | /// @param interfaceId the 4 byte interface signature 10 | function supportsInterface(bytes4 interfaceId) external view returns (bool); 11 | } 12 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | tests: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v2 12 | - name: Install Foundry 13 | uses: onbjerg/foundry-toolchain@v1 14 | with: 15 | version: nightly 16 | - name: Install Dependencies 17 | run: yarn 18 | - name: Update Modules 19 | run: yarn sync 20 | - name: Run Tests 21 | run: yarn test -------------------------------------------------------------------------------- /.github/workflows/lints.yml: -------------------------------------------------------------------------------- 1 | name: Lints 2 | 3 | on: [push] 4 | 5 | jobs: 6 | lints: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v2 12 | 13 | - name: Install Foundry 14 | uses: onbjerg/foundry-toolchain@v1 15 | with: 16 | version: nightly 17 | 18 | - name: Install Dependencies 19 | run: yarn 20 | - name: Update Modules 21 | run: yarn sync 22 | - name: Run lints 23 | run: yarn lint -------------------------------------------------------------------------------- /.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "plugins": ["prettier"], 4 | "rules": { 5 | "code-complexity": ["error", 8], 6 | "compiler-version": ["error", ">=0.5.8"], 7 | "const-name-snakecase": "off", 8 | "constructor-syntax": "error", 9 | "func-visibility": ["error", { "ignoreConstructors": true }], 10 | "max-line-length": ["error", 120], 11 | "not-rely-on-time": "off", 12 | "prettier/prettier": [ 13 | "error", 14 | { 15 | "endOfLine": "auto" 16 | } 17 | ], 18 | "reason-string": ["warn", { "maxLength": 64 }] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.dapprc: -------------------------------------------------------------------------------- 1 | # Basic build/test configuration. 2 | export DAPP_SOLC_VERSION=0.8.11 3 | export DAPP_BUILD_OPTIMIZE=1 4 | export DAPP_BUILD_OPTIMIZE_RUNS=8000 5 | export DAPP_LINK_TEST_LIBRARIES=0 6 | export DAPP_TEST_VERBOSITY=1 7 | export DAPP_TEST_SMTTIMEOUT=500000 8 | export DAPP_REMAPPINGS=$(cat remappings.txt) 9 | 10 | # These normally default to 0 which breaks some tests. 11 | export DAPP_TEST_TIMESTAMP=1000000000 12 | export DAPP_TEST_NUMBER=10000000 13 | 14 | if [ "$DEEP_FUZZ" = "true" ] 15 | then 16 | export DAPP_TEST_FUZZ_RUNS=10000 # Fuzz for a long time if DEEP_FUZZ is set to true. 17 | else 18 | export DAPP_TEST_FUZZ_RUNS=100 # Only fuzz briefly if DEEP_FUZZ is not set to true. 19 | fi -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twam", 3 | "description": "Time Weighted Asset Mints", 4 | "author": "Andreas Bigger ", 5 | "license": "AGPL-3.0-only", 6 | "version": "1.4.0", 7 | "files": [ 8 | "src/**/*.sol" 9 | ], 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/abigger87/twam.git" 13 | }, 14 | "devDependencies": { 15 | "prettier": "^2.3.1", 16 | "prettier-plugin-solidity": "^1.0.0-beta.13" 17 | }, 18 | "scripts": { 19 | "setup": "make clean && make build", 20 | "sync": "make update", 21 | "test": "make test", 22 | "snapshot": "make snapshot", 23 | "lint": "make lint" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/utils/DSTestPlus.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | // forge-std imports 5 | import {Vm} from "@std/Vm.sol"; 6 | import {stdCheats, stdError} from "@std/stdlib.sol"; 7 | 8 | // solmate Imports 9 | import {ERC20} from "@solmate/tokens/ERC20.sol"; 10 | import {DSTestPlus as DSTest} from "@solmate/test/utils/DSTestPlus.sol"; 11 | 12 | contract DSTestPlus is DSTest, stdCheats { 13 | 14 | /// @dev Use forge-std Vm logic 15 | Vm public constant vm = Vm(HEVM_ADDRESS); 16 | 17 | /// @dev Compares ERC20 Tokens 18 | function assertERC20Eq(ERC20 erc1, ERC20 erc2) internal { 19 | assertEq(address(erc1), address(erc2)); 20 | } 21 | } -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # include .env file and export its env vars 2 | # (-include to ignore error if it does not exist) 3 | -include .env 4 | 5 | all: clean remove install update solc build dappbuild 6 | 7 | # Install proper solc version. 8 | solc:; nix-env -f https://github.com/dapphub/dapptools/archive/master.tar.gz -iA solc-static-versions.solc_0_8_11 9 | 10 | # Clean the repo 11 | clean :; forge clean 12 | 13 | # Remove modules 14 | remove :; rm -rf .gitmodules && rm -rf .git/modules/* && rm -rf lib && touch .gitmodules && git add . && git commit -m "modules" 15 | 16 | # Install the Modules 17 | install :; forge install dapphub/ds-test && forge install rari-capital/solmate && forge install brockelmore/forge-std && forge install ZeframLou/clones-with-immutable-args 18 | 19 | # Update Dependencies 20 | update:; forge update 21 | 22 | # Builds 23 | build :; forge clean && forge build --optimize --optimize-runs 1000000 24 | dappbuild :; dapp build 25 | 26 | # Tests 27 | test :; forge clean && forge test --optimize --optimize-runs 1000000 -v # --ffi # enable if you need the `ffi` cheat code on HEVM 28 | 29 | # Lints 30 | lint :; prettier --write src/**/*.sol && prettier --write src/*.sol 31 | 32 | # Generate Gas Snapshots 33 | snapshot :; forge clean && forge snapshot --optimize --optimize-runs 1000000 -------------------------------------------------------------------------------- /src/interfaces/IERC20.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | /// @title ERC20 Interface 5 | /// @dev https://eips.ethereum.org/EIPS/eip-20 6 | /// @author Andreas Bigger 7 | interface IERC20 { 8 | /// @dev The circulating supply of tokens 9 | function totalSupply() external view returns (uint256); 10 | 11 | /// @dev The number of tokens owned by the account 12 | /// @param account The address to get the balance for 13 | function balanceOf(address account) external view returns (uint256); 14 | 15 | /// @dev Transfers the specified amount of tokens to the recipient from the sender 16 | function transfer(address recipient, uint256 amount) external returns (bool); 17 | 18 | /// @dev The amount of tokens the spender is permitted to transfer from the owner 19 | function allowance(address owner, address spender) external view returns (uint256); 20 | 21 | /// @dev Permits a spender to transfer an amount of tokens 22 | function approve(address spender, uint256 amount) external returns (bool); 23 | 24 | /// @dev Transfers tokens from the sender using the caller's allowance 25 | function transferFrom( 26 | address sender, 27 | address recipient, 28 | uint256 amount 29 | ) external returns (bool); 30 | 31 | /// @dev Emitted when tokens are transfered 32 | /// @param from The address that is sending the tokens 33 | /// @param to The token recipient 34 | /// @param value The number of tokens 35 | event Transfer(address indexed from, address indexed to, uint256 value); 36 | 37 | /// @dev Emitted when an owner permits a spender 38 | /// @param owner The token owner 39 | /// @param spender The permitted spender 40 | /// @param value The number of tokens 41 | event Approval(address indexed owner, address indexed spender, uint256 value); 42 | } 43 | -------------------------------------------------------------------------------- /src/interfaces/IERC721.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | import {IERC165} from "./IERC165.sol"; 5 | 6 | /// @title ERC721 Interface 7 | /// @dev https://eips.ethereum.org/EIPS/eip-721 8 | /// @author Andreas Bigger 9 | interface IERC721 is IERC165 { 10 | /// @dev Emitted when a token is transferred 11 | event Transfer( 12 | address indexed from, 13 | address indexed to, 14 | uint256 indexed tokenId 15 | ); 16 | 17 | /// @dev Emitted when a token owner approves `approved` 18 | event Approval( 19 | address indexed owner, 20 | address indexed approved, 21 | uint256 indexed tokenId 22 | ); 23 | 24 | /// @dev Emitted when `owner` enables or disables `operator` for all tokens 25 | event ApprovalForAll( 26 | address indexed owner, 27 | address indexed operator, 28 | bool approved 29 | ); 30 | 31 | /// @dev Returns the number of tokens owned by `owner` 32 | function balanceOf(address owner) external view returns (uint256 balance); 33 | 34 | /// @dev Returns the owner of token with id `tokenId` 35 | function ownerOf(uint256 tokenId) external view returns (address owner); 36 | 37 | /// @dev Safely transfers the token with id `tokenId` 38 | /// @dev Requires the sender to be approved through an `approve` or `setApprovalForAll` 39 | /// @dev Emits a Transfer Event 40 | function safeTransferFrom( 41 | address from, 42 | address to, 43 | uint256 tokenId 44 | ) external; 45 | 46 | /// @dev Transfers the token with id `tokenId` 47 | /// @dev Requires the sender to be approved through an `approve` or `setApprovalForAll` 48 | /// @dev Emits a Transfer Event 49 | function transferFrom( 50 | address from, 51 | address to, 52 | uint256 tokenId 53 | ) external; 54 | 55 | /// @dev Approves `to` to transfer the given token 56 | /// @dev Approval is reset on transfer 57 | /// @dev Caller must be the owner or approved 58 | /// @dev Only one address can be approved at a time 59 | /// @dev Emits an Approval Event 60 | function approve(address to, uint256 tokenId) external; 61 | 62 | /// @dev Returns the address approved for the given token 63 | function getApproved(uint256 tokenId) 64 | external 65 | view 66 | returns (address operator); 67 | 68 | /// @dev Sets an operator as approved or disallowed for all tokens owned by the caller 69 | /// @dev Emits an ApprovalForAll Event 70 | function setApprovalForAll(address operator, bool _approved) external; 71 | 72 | /// @dev Returns if the operator is allowed approved for owner's tokens 73 | function isApprovedForAll(address owner, address operator) 74 | external 75 | view 76 | returns (bool); 77 | 78 | /// @dev Safely transfers a token with id `tokenId` 79 | /// @dev Emits a Transfer Event 80 | function safeTransferFrom( 81 | address from, 82 | address to, 83 | uint256 tokenId, 84 | bytes calldata data 85 | ) external; 86 | } 87 | -------------------------------------------------------------------------------- /src/test/TwamFactory.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | 5 | import {stdError} from "@std/stdlib.sol"; 6 | 7 | import {MockERC20} from "@solmate/test/utils/mocks/MockERC20.sol"; 8 | import {MockERC721} from "@solmate/test/utils/mocks/MockERC721.sol"; 9 | import {SafeCastLib} from "@solmate/utils/SafeCastLib.sol"; 10 | 11 | import {DSTestPlus} from "./utils/DSTestPlus.sol"; 12 | import {TwamBase} from "../TwamBase.sol"; 13 | import {TwamFactory} from "../TwamFactory.sol"; 14 | 15 | /// @dev DSTestPlus inherits stdCheats 16 | contract TwamFactoryTest is DSTestPlus { 17 | 18 | /// @dev Contracts 19 | TwamBase public twamBase; // Twam Base (Clone) 20 | TwamFactory public twamFactory; // Twam Factory 21 | MockERC20 public depositToken; // Mock ERC20 Deposit Token 22 | MockERC721 public badMockERC721; // Mock Invalid ERC721 Token 23 | MockERC721 public mockToken; // Mock ERC721 Token 24 | 25 | /// @dev Constants 26 | uint256 public constant TOKEN_SUPPLY = 10_000; 27 | address public constant COORDINATOR = 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B; 28 | 29 | /// @notice Testing suite precursors 30 | function setUp() public { 31 | TwamBase exampleClone = new TwamBase(); 32 | twamFactory = new TwamFactory(exampleClone); 33 | 34 | // Creat Mock Tokens 35 | depositToken = new MockERC20("Token", "TKN", 18); 36 | mockToken = new MockERC721("Token", "TKN"); 37 | badMockERC721 = new MockERC721("Token", "TKN"); 38 | } 39 | 40 | /// @notice Test onERC721Received 41 | function testOnERC721Received() public { 42 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 43 | 44 | mockToken.mint(COORDINATOR, 0); 45 | 46 | // This should work 47 | mockToken.approve(COORDINATOR, 0); 48 | mockToken.safeTransferFrom( 49 | COORDINATOR, // from 50 | address(twamFactory), // to 51 | 0, // id 52 | abi.encode(address(mockToken)) // data 53 | ); 54 | 55 | // Verify we correctly set the approved creator 56 | assert(twamFactory.approvedCreator(address(mockToken)) != address(0)); 57 | assert(twamFactory.approvedCreator(address(mockToken)) == COORDINATOR); 58 | 59 | // This should fail since the session has already been created 60 | vm.expectRevert("WRONG_FROM"); 61 | mockToken.transferFrom(COORDINATOR, address(twamFactory), 0); 62 | 63 | vm.stopPrank(); 64 | } 65 | 66 | /// @notice Creates a Twam from Factory 67 | function testCreateTwam() public { 68 | uint64 t = SafeCastLib.safeCastTo64(block.timestamp); 69 | 70 | // Transfer the NFT to verify ownership 71 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 72 | mockToken.mint(COORDINATOR, 0); 73 | mockToken.approve(COORDINATOR, 0); 74 | mockToken.safeTransferFrom( 75 | COORDINATOR, // from 76 | address(twamFactory), // to 77 | 0, // id 78 | abi.encode(address(mockToken)) // data 79 | ); 80 | vm.stopPrank(); 81 | 82 | // We should expect a NotApproved revert when not from the COORDINATOR 83 | vm.expectRevert(abi.encodeWithSignature( 84 | "NotApproved(address,address,address)", 85 | address(this), // Msg Sender 86 | COORDINATOR, // Approved Creator 87 | address(mockToken) // ERC721 Token 88 | )); 89 | twamBase = twamFactory.createTwam( 90 | address(mockToken), // token 91 | COORDINATOR, // coordinator 92 | t + 10, // allocationStart, 93 | t + 15, // allocationEnd, 94 | t + 20, // mintingStart, 95 | t + 25, // mintingEnd, 96 | 100, // minPrice, 97 | address(depositToken), // depositToken 98 | TOKEN_SUPPLY, // maxMintingAmount, 99 | 1 // rolloverOption 100 | ); 101 | 102 | // Switch back to COORDINATOR context 103 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 104 | 105 | // Should still fail without senting the MaxMintingAmount 106 | vm.expectRevert(abi.encodeWithSignature( 107 | "RequireMintedERC721Tokens(uint256,uint256)", 108 | 1, 109 | TOKEN_SUPPLY 110 | )); 111 | twamBase = twamFactory.createTwam( 112 | address(mockToken), // token 113 | COORDINATOR, // coordinator 114 | t + 10, // allocationStart, 115 | t + 15, // allocationEnd, 116 | t + 20, // mintingStart, 117 | t + 25, // mintingEnd, 118 | 100, // minPrice, 119 | address(depositToken), // depositToken 120 | TOKEN_SUPPLY, // maxMintingAmount, 121 | 1 // rolloverOption 122 | ); 123 | 124 | // Mint all erc721 tokens to the twam factory 125 | // This can be practically done by modifying the twam factory to be the initial owner 126 | for(uint256 i = 1; i < TOKEN_SUPPLY; i++) { 127 | mockToken.mint(address(twamFactory), i); 128 | } 129 | 130 | // Successfully create a TWAM session 131 | twamBase = twamFactory.createTwam( 132 | address(mockToken), // token 133 | COORDINATOR, // coordinator 134 | t + 10, // allocationStart, 135 | t + 15, // allocationEnd, 136 | t + 20, // mintingStart, 137 | t + 25, // mintingEnd, 138 | 100, // minPrice, 139 | address(depositToken), // depositToken 140 | TOKEN_SUPPLY, // maxMintingAmount, 141 | 1 // rolloverOption 142 | ); 143 | 144 | vm.stopPrank(); 145 | 146 | // Fail to create a duplicate session 147 | vm.expectRevert(abi.encodeWithSignature( 148 | "DuplicateSession(address,address)", 149 | address(this), 150 | address(mockToken) 151 | )); 152 | twamBase = twamFactory.createTwam( 153 | address(mockToken), // token 154 | COORDINATOR, // coordinator 155 | t + 10, // allocationStart, 156 | t + 15, // allocationEnd, 157 | t + 20, // mintingStart, 158 | t + 25, // mintingEnd, 159 | 100, // minPrice, 160 | address(depositToken), // depositToken 161 | TOKEN_SUPPLY, // maxMintingAmount, 162 | 1 // rolloverOption 163 | ); 164 | 165 | // Make sure factory state updates 166 | assert(twamFactory.createdTwams(address(mockToken)) != address(0)); 167 | assert(twamFactory.sessions(1) != address(0)); 168 | assert(twamFactory.sessionId() == 2); 169 | } 170 | } -------------------------------------------------------------------------------- /src/TwamFactory.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | import {ERC721TokenReceiver} from "@solmate/tokens/ERC721.sol"; 5 | import {ClonesWithImmutableArgs} from "@clones/ClonesWithImmutableArgs.sol"; 6 | 7 | import {TwamBase} from "./TwamBase.sol"; 8 | import {IERC721} from "./interfaces/IERC721.sol"; 9 | 10 | //////////////////////////////////////////////////// 11 | /// CUSTOM ERRORS /// 12 | //////////////////////////////////////////////////// 13 | 14 | /// Duplicate Session 15 | /// @param sender The message sender 16 | /// @param token The address of the ERC721 Token 17 | error DuplicateSession(address sender, address token); 18 | 19 | /// Not Approved 20 | /// The sender is not approved to create the session for the given ERC721 token 21 | /// @param sender The message sender 22 | /// @param approved The address of the approved creator 23 | /// @param token The address of the ERC721 Token 24 | error NotApproved(address sender, address approved, address token); 25 | 26 | /// Bad Session Bounds 27 | /// @param allocationStart The session's allocation period start 28 | /// @param allocationEnd The session's allocation period end 29 | /// @param mintingStart The session's minting period start 30 | /// @param mintingEnd The session's minting period end 31 | error BadSessionBounds(uint64 allocationStart, uint64 allocationEnd, uint64 mintingStart, uint64 mintingEnd); 32 | 33 | /// Require the ERC721 tokens to already be transferred to the twam contract 34 | /// Enables permissionless session creation 35 | /// @param balanceOfThis The ERC721 balance of the twam contract 36 | /// @param maxMintingAmount The maxmum number of ERC721s to mint 37 | error RequireMintedERC721Tokens(uint256 balanceOfThis, uint256 maxMintingAmount); 38 | 39 | /// Session Overwrite 40 | error SessionOverwrite(); 41 | 42 | /// Sender is not owner 43 | error SenderNotOwner(); 44 | 45 | //////////////////////////////////////////////////// 46 | /// Twam Factory /// 47 | //////////////////////////////////////////////////// 48 | 49 | /// @title TwamFactory 50 | /// @notice TWAM Deployment Factory 51 | /// @author Andreas Bigger 52 | /// @dev Adapted from https://github.com/ZeframLou/vested-erc20/blob/main/src/VestedERC20Factory.sol 53 | contract TwamFactory is ERC721TokenReceiver { 54 | /// @dev Use CloneWithCallData library for cheap deployment 55 | /// @dev Uses a modified minimal proxy pattern 56 | using ClonesWithImmutableArgs for address; 57 | 58 | /// @dev Emit a creation event to track twams 59 | event TwamDeployed(TwamBase twam); 60 | 61 | /// @notice The TwamBase implementation 62 | TwamBase public immutable implementation; 63 | 64 | /// @dev Only addresses that have transferred the erc721 tokens to this address can create a session 65 | /// @dev Maps ERC721 => user 66 | mapping(address => address) public approvedCreator; 67 | 68 | /// @notice Tracks created TWAM sessions 69 | /// @dev Maps ERC721 => deployed TwamBase Contract 70 | mapping(address => address) public createdTwams; 71 | 72 | /// @notice Tracks TWAM Sessions by ID 73 | mapping(uint256 => address) public sessions; 74 | 75 | /// @notice The next session ID 76 | /// @dev initialized to 1 for cheaper initial loads 77 | uint256 public sessionId = 1; 78 | 79 | /// @notice Creates the Factory with the given TwamBase implementation 80 | /// @param implementation_ The TwamBase implementation 81 | constructor(TwamBase implementation_) { 82 | implementation = implementation_; 83 | } 84 | 85 | /// @notice Creates a TWAM 86 | /// @param token The ERC721 Token 87 | /// @param coordinator The session coordinator who controls the session 88 | /// @param allocationStart When the allocation period begins 89 | /// @param allocationEnd When the allocation period ends 90 | /// @param mintingStart When the minting period begins 91 | /// @param mintingEnd When the minting period ends 92 | /// @param minPrice The minimum token price for minting 93 | /// @param depositToken The token to pay for minting 94 | /// @param maxMintingAmount The maximum amount of tokens to mint (must be minted to this contract) 95 | /// @param rolloverOption What happens when the minting period ends and the session is over; one of {1, 2, 3} 96 | function createTwam( 97 | address token, 98 | address coordinator, 99 | uint64 allocationStart, 100 | uint64 allocationEnd, 101 | uint64 mintingStart, 102 | uint64 mintingEnd, 103 | uint256 minPrice, 104 | address depositToken, 105 | uint256 maxMintingAmount, 106 | uint8 rolloverOption 107 | ) external returns (TwamBase twamBase) { 108 | // Prevent Overwriting Sessions 109 | if (createdTwams[token] != address(0) || token == address(0)) { 110 | revert DuplicateSession(msg.sender, token); 111 | } 112 | 113 | // For Permissionless Session Creation 114 | // We check that the sender is the approvedCreator 115 | if (approvedCreator[token] != msg.sender) { 116 | revert NotApproved(msg.sender, approvedCreator[token], token); 117 | } 118 | 119 | // We also have to make sure this address has a sufficient balance of ERC721 tokens for the session 120 | // This can be done by setting the ERC721.balanceOf(address(TwamFactory)) to the maxMintingAmount on ERC721 contract deployment 121 | uint256 balanceOfThis = IERC721(token).balanceOf(address(this)); 122 | if (balanceOfThis < maxMintingAmount) revert RequireMintedERC721Tokens(balanceOfThis, maxMintingAmount); 123 | 124 | // Validate Session Bounds 125 | if ( 126 | allocationStart > allocationEnd 127 | || mintingStart > mintingEnd 128 | || mintingStart < allocationEnd 129 | ) { 130 | revert BadSessionBounds(allocationStart, allocationEnd, mintingStart, mintingEnd); 131 | } 132 | 133 | // We can abi encodePacked instead of manually packing 134 | bytes memory data = abi.encodePacked( 135 | token, 136 | coordinator, 137 | allocationStart, 138 | allocationEnd, 139 | mintingStart, 140 | mintingEnd, 141 | minPrice, 142 | maxMintingAmount, 143 | depositToken, 144 | rolloverOption, 145 | sessionId, 146 | address(this) 147 | ); 148 | 149 | // Create the TWAM 150 | twamBase = TwamBase( 151 | address(implementation).clone(data) 152 | ); 153 | emit TwamDeployed(twamBase); 154 | 155 | // Set approval for all the ERC721 Tokens 156 | IERC721(token).setApprovalForAll(address(twamBase), true); 157 | 158 | // Record Creation 159 | createdTwams[token] = address(twamBase); 160 | sessions[sessionId] = address(twamBase); 161 | sessionId += 1; 162 | } 163 | 164 | /// @notice TwamFactory receives ERC721 tokens to allow permissionless session creation 165 | function onERC721Received( 166 | address _operator, 167 | address _from, 168 | uint256 _id, 169 | bytes calldata _data 170 | ) public virtual override returns (bytes4) { 171 | address token = abi.decode(_data, (address)); 172 | 173 | // Make sure there isn't already an approved creator 174 | if (approvedCreator[token] != address(0)) { 175 | revert SessionOverwrite(); 176 | } 177 | 178 | // Verify this token is being transferred by checking the balance of _from 179 | if (IERC721(token).ownerOf(_id) != address(this)) { 180 | revert SenderNotOwner(); 181 | } 182 | 183 | // Approve the sender as the session creator for 184 | approvedCreator[token] = _from; 185 | 186 | // Finally, return the selector to complete the transfer 187 | return ERC721TokenReceiver.onERC721Received.selector; 188 | } 189 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TWAM • [![tests](https://github.com/abigger87/twam/actions/workflows/tests.yml/badge.svg)](https://github.com/abigger87/twam/actions/workflows/tests.yml) [![lints](https://github.com/abigger87/twam/actions/workflows/lints.yml/badge.svg)](https://github.com/abigger87/twam/actions/workflows/lints.yml) ![GitHub](https://img.shields.io/github/license/abigger87/twam) ![GitHub package.json version](https://img.shields.io/github/package-json/v/abigger87/twam) 2 | 3 | ##### _Time Weighted Asset Mints_ 4 | 5 | A minting harness enabling time-weighted assets to determine minting prices. 6 | 7 | ## How it works 8 | 9 | [TwamFactory](./src/TwamFactory.sol) manages creating TWAM Sessions. 10 | 11 | A given TWAM Session can be created permissionlessly. With two requirements: 12 | - The session creator sets the TwamFactory ERC721 token balance to at least `maxMiningAmount`. 13 | - The session creator then transfers 1 ERC721 token to the TwamFactory to verify they are the owner of the ERC721 Tokens. 14 | 15 | The singular ERC721 Token transfer is required to trigger the [TwamFactory](./src/TwamFactory.sol)'s `onERC721Received` hook that sets the approved session creator. 16 | 17 | This comes with assumptions: 18 | - The creator owns all ERC721 Tokens to start with before doing a sale (or they risk another owner frontrunning the session creation). 19 | - ERC721 Tokens [0-maxMintingAmount] are owned by the TwamFactory since sales are done sequentially. 20 | 21 | When a TWAM Session is created using the [TwamFactory](./src/TwamFactory.sol)'s `createTwam` function, a minimal proxy contract is created using the arguments as immutables (h/t [ZeframLou](https://github.com/ZeframLou/clones-with-immutable-args)). 22 | 23 | #### TWAM Session Parameters 24 | 25 | `token` - The address of the ERC721 Contract. 26 | `coordinator` - The sale profit receiver. 27 | `allocationStart` - The timestamp when the allocation period begins. 28 | `allocationEnd` - The timestamp when the allocation period ends. 29 | `mintingStart` - The timestamp when the minting period begins. 30 | `mintingEnd` - The timestamp when the minting period ends. 31 | `minPrice` - The minimum price per ERC721 token. 32 | `depositToken` - The address of the ERC20 token that is paid by users. 33 | `maxMintingAmount` - The maximum number of ERC721 Tokens available for sale. 34 | `rolloverOption` - Option in {1, 2, 3} indicating what happens when a Session ends. 35 | 36 | 37 | #### TWAM Session Lifecycle 38 | 39 | For a given mint's `allocationPeriod` (let's use 24 hours), a given type of asset can be deposited into the [twam](./src/TWAM.sol) contract. Note: during the `allocationPeriod`, the deposit token **cannot** be withdrawn. 40 | 41 | Additionally, a loss penalty is calculated with respect to when you deposit in the allocation period. The later you deposit, the more of a penalty you will occur if you choose to forgo minting. This prevents spoofing allocations, helping those who are genuinely interested in minting the ERC721 token. 42 | 43 | NOTE: if someones total deposits in a session aren't enough to mint at least one ERC721 token based on price, withdrawals are allowed **without** a penalty. 44 | 45 | 46 | Once the `allocationPeriod` ends, a cooldown period begins with a length of `mintingStart` - `allocationEnd`. At this time, no more deposits are permitted. 47 | 48 | Note: there may be no cooldown if `mintingStart` = `allocationEnd`. 49 | 50 | At the beginning of the minting period `mintingStart`, each ERC721 can be minted at the price equal to (total allocated assets) / (maximum supply ERC721 tokens) as long as it exceeds the `minPrice` TWAM session parameter. 51 | 52 | If the `minPrice` is not reached, minting is prohibited, and nothing happens during the minting period. 53 | 54 | If all tokens are minted at the end of the minting period, the session is completed. 55 | 56 | Otherwise (when the `minimumPrice` isn't met or not all tokens are minted), one of three options are available based on the Session's `rolloverOption`: 57 | 1. The TWAM Session starts over again. 58 | 2. Minting is enabled at the max{`resultPrice`, `minimumPrice`}. 59 | 3. The session is ended. 60 | 61 | The Session's `rolloverOption` may only be one of these three. 62 | 63 | 64 | #### Minter Functions 65 | 66 | `deposit(uint256)` - Deposits a `uint256` amount into the Session during the allocation period. 67 | `withdraw(uint256)` - Allows a user to withdraw after the Session ends (`mintingEnd` is passed) and the `rolloverOption` is 3. 68 | `mint(uint256)` - Mints a number of ERC721 tokens to a user during the minting period as calculated by `uint256` / `resultPrice` where `resultPrice` is the final price per ERC721 token. 69 | `forgo(uint256)` - Allows a user to withdraw their deposited token, giving up their minting allocation. This may incur a loss penalty as a function of when the deposits are made. 70 | 71 | 72 | #### Coordinator Functions 73 | 74 | `rollover()` - Allows the coordinator to rollover the Session if the minting is over - only sets the `rolloverOffset` if the `rolloverOption` is one of {1,2}. 75 | `withdrawRewards()` - Withdraws the deposit tokens earned by the coordinator in exchange for the minted ERC721 Tokens. 76 | 77 | ## Blueprint 78 | 79 | ```ml 80 | lib 81 | ├─ clones-with-immutable-args — https://github.com/ZeframLou/clones-with-immutable-args 82 | ├─ ds-test — https://github.com/dapphub/ds-test 83 | ├─ forge-std — https://github.com/brockelmore/forge-std 84 | ├─ solmate — https://github.com/Rari-Capital/solmate 85 | src 86 | ├─ tests 87 | │ ├─ TwamBase.t — "Primary TWAM Functionality Tests" 88 | │ └─ TwamFactory.t — "Proxy and TwamBase Deployment Tests" 89 | ├─ TwamBase — "Time Weighted Asset Mint Logic Contract" 90 | └─ TwamFactory — "Minimal Proxy Deployer" 91 | ``` 92 | 93 | ## Development 94 | 95 | ### Install DappTools 96 | 97 | Install DappTools using their [installation guide](https://github.com/dapphub/dapptools#installation). 98 | 99 | ### First time with Forge/Foundry? 100 | 101 | Don't have [rust](https://www.rust-lang.org/tools/install) installed? 102 | Run 103 | ```bash 104 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 105 | ``` 106 | 107 | Then, install [foundry](https://github.com/gakonst/foundry) with: 108 | ```bash 109 | cargo install --git https://github.com/gakonst/foundry --bin forge --locked 110 | ``` 111 | 112 | ### Setup and Build 113 | 114 | ```bash 115 | make 116 | ``` 117 | 118 | ### Run Tests 119 | 120 | ```bash 121 | make test 122 | ``` 123 | 124 | ## License 125 | 126 | [AGPL-3.0-only](https://github.com/abigger87/twam/blob/master/LICENSE) 127 | 128 | # Acknowledgements 129 | 130 | - [foundry](https://github.com/gakonst/foundry) 131 | - [solmate](https://github.com/Rari-Capital/solmate) 132 | - [forge-std](https://github.com/brockelmore/forge-std) 133 | - [clones-with-immutable-args](https://github.com/ZeframLou/clones-with-immutable-args) 134 | - [foundry-toolchain](https://github.com/onbjerg/foundry-toolchain) by [onbjerg](https://github.com/onbjerg). 135 | - [forge-starter](https://github.com/abigger87/forge-starter) by [abigger87](https://github.com/abigger87). 136 | - [forge-template](https://github.com/FrankieIsLost/forge-template) by [FrankieIsLost](https://github.com/FrankieIsLost). 137 | - [Georgios Konstantopoulos](https://github.com/gakonst) for [forge-template](https://github.com/gakonst/forge-template) resource. 138 | 139 | ## Disclaimer 140 | 141 | _These smart contracts are being provided as is. No guarantee, representation or warranty is being made, express or implied, as to the safety or correctness of the user interface or the smart contracts. They have not been audited and as such there can be no assurance they will work as intended, and users may experience delays, failures, errors, omissions, loss of transmitted information or loss of funds. The creators are not liable for any of the foregoing. Users should proceed with caution and use at their own risk._ 142 | -------------------------------------------------------------------------------- /src/TwamBase.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | import {Clone} from "@clones/Clone.sol"; 5 | import {SafeCastLib} from "@solmate/utils/SafeCastLib.sol"; 6 | import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol"; 7 | 8 | import {IERC20} from "./interfaces/IERC20.sol"; 9 | import {IERC721} from "./interfaces/IERC721.sol"; 10 | 11 | //////////////////////////////////////////////////// 12 | /// CUSTOM ERRORS /// 13 | //////////////////////////////////////////////////// 14 | 15 | /// Invalid Session 16 | /// @param sessionId The session's id 17 | error InvalidSession(uint256 sessionId); 18 | 19 | /// Not during the Allocation Period 20 | /// @param blockNumber block.number 21 | /// @param allocationStart The block number that marks when the allocation starts 22 | /// @param allocationEnd The block number that marks when the allocation ends 23 | error NonAllocation(uint256 blockNumber, uint64 allocationStart, uint64 allocationEnd); 24 | 25 | /// Not during the Minting Period 26 | /// @param blockNumber block.number 27 | /// @param mintingStart The block number that marks when the minting period starts 28 | /// @param mintingEnd The block number that marks when the minting period ends 29 | error NonMinting(uint256 blockNumber, uint64 mintingStart, uint64 mintingEnd); 30 | 31 | /// Make sure the sender has enough deposits 32 | /// @param sender The message sender 33 | /// @param deposits The user's deposits in the session 34 | /// @param amount The amount a user want's to mint with 35 | error InsufficientDesposits(address sender, uint256 deposits, uint256 amount); 36 | 37 | /// The Minting Period is not Over 38 | /// @param blockNumber The current block.number 39 | /// @param mintingEnd When the session minting period ends 40 | error MintingNotOver(uint256 blockNumber, uint64 mintingEnd); 41 | 42 | /// Invalid Coordinator 43 | /// @param sender The msg sender 44 | /// @param coordinator The expected session coordinator 45 | error InvalidCoordinator(address sender, address coordinator); 46 | 47 | //////////////////////////////////////////////////// 48 | /// TWAM /// 49 | //////////////////////////////////////////////////// 50 | 51 | /// @title TwamBase 52 | /// @notice Time Weighted Asset Minting Base Clone 53 | /// @author Andreas Bigger 54 | contract TwamBase is Clone { 55 | using FixedPointMathLib for uint256; 56 | 57 | /// @dev Immutable Session Variables are stored in Calldata using ClonesWithImmutableArgs 58 | 59 | /// @notice Maps a session to the amount of deposits 60 | mapping(uint256 => uint256) public totalDeposits; 61 | 62 | /// @notice Maps a session id to the resulting session price 63 | mapping(uint256 => uint256) public resultPrice; 64 | 65 | /// @notice Maps a session id to the next token id to mint 66 | mapping(uint256 => uint256) public nextMintId; 67 | 68 | /// @notice Maps a user and session id to their deposits 69 | mapping(address => mapping(uint256 => uint256)) public deposits; 70 | 71 | /// @notice Session Rewards for Coordinators 72 | /// @dev Maps coordinator => token => rewardAmount 73 | mapping(address => mapping(address => uint256)) public rewards; 74 | 75 | /// @notice Loss Penalty for each depositor 76 | /// @dev Fixed-point number where YAD represents 100% 77 | /// @dev Updates calculated using weighted average 78 | /// @dev Maps user => session id => lossPenalty 79 | mapping(address => mapping(uint256 => uint256)) public lossPenalty; 80 | 81 | /// @notice The Loss Penalty base unit 82 | uint256 public constant YAD = 1e8; 83 | 84 | /// @notice Token Ids for the ERC721s 85 | mapping(address => uint256) private tokenIds; 86 | 87 | /// @dev A rollover offset 88 | /// @dev Maps a session Id to the rolloverOffset 89 | /// @dev The rolloverOffset equals block.timestamp when rollover() is called 90 | mapping(uint256 => uint256) private rolloverOffset; 91 | 92 | //////////////////////////////////////////////////// 93 | /// SESSION MANAGEMENT LOGIC /// 94 | //////////////////////////////////////////////////// 95 | 96 | /// @notice Allows the coordinator to rollover 97 | /// @notice Requires the minting period to be over 98 | function rollover() public { 99 | // Read Calldata Immutables 100 | address coordinator = readCoordinator(); 101 | uint64 mintingEnd = readMintingEnd(); 102 | uint256 sessionId = readSessionId(); 103 | uint8 rolloverOption = readRolloverOption(); 104 | 105 | // Validate Coordinator 106 | if (msg.sender != coordinator) { 107 | revert InvalidCoordinator(msg.sender, coordinator); 108 | } 109 | 110 | // MSTORE timestamp is cheaper than double calls 111 | uint256 timestamp = block.timestamp; 112 | 113 | // Require Minting to be complete 114 | if (timestamp < mintingEnd) { 115 | revert MintingNotOver(timestamp, mintingEnd); 116 | } 117 | 118 | // Rollover Options 119 | // 1. Restart the twam 120 | // 2. Mint at resulting price or minimum if not reached 121 | // 3. Close Session 122 | if(rolloverOption != 3) { 123 | // For both options 1 & 2, we can just set the rolloverOffset 124 | // and check it inside our functions 125 | rolloverOffset[sessionId] = timestamp; 126 | } 127 | } 128 | 129 | /// @notice Allows the coordinator to withdraw session rewards 130 | function withdrawRewards() public { 131 | // Read Calldata Immutables 132 | address depositToken = readDepositToken(); 133 | 134 | // Transfer rewards 135 | uint256 rewardAmount = rewards[msg.sender][depositToken]; 136 | rewards[msg.sender][depositToken] = 0; 137 | IERC20(depositToken).transfer(msg.sender, rewardAmount); 138 | } 139 | 140 | //////////////////////////////////////////////////// 141 | /// SESSION ALLOCATION PERIOD /// 142 | //////////////////////////////////////////////////// 143 | 144 | /// @notice Deposit a deposit token into a session 145 | /// @dev requires approval of the deposit token 146 | /// @param amount The amount of the deposit token to deposit 147 | function deposit(uint256 amount) public { 148 | // Read Calldata Immutables 149 | uint256 sessionId = readSessionId(); 150 | uint64 allocationStart = readAllocationStart(); 151 | uint64 allocationEnd = readAllocationEnd(); 152 | address depositToken = readDepositToken(); 153 | 154 | // MSTORE timestamp is cheaper than double calls 155 | uint256 timestamp = block.timestamp; 156 | 157 | // Make sure the session is in the allocation period 158 | if (timestamp > allocationEnd || timestamp < allocationStart) { 159 | revert NonAllocation(timestamp, allocationStart, allocationEnd); 160 | } 161 | 162 | // Update a user's loss penalty 163 | uint256 currLossPenalty = lossPenalty[msg.sender][sessionId]; 164 | 165 | // Calculate Loss Penalty 166 | uint256 newLossPenalty = simulateLossPenalty(amount, allocationStart, allocationEnd, timestamp); 167 | if (newLossPenalty > YAD) newLossPenalty = YAD; 168 | 169 | // Set the penalty if 0 170 | if(currLossPenalty == 0) { 171 | lossPenalty[msg.sender][sessionId] = newLossPenalty; 172 | } else { 173 | // Calculate a weighted penalty based on amount 174 | uint256 user_deposits = deposits[msg.sender][sessionId]; 175 | lossPenalty[msg.sender][sessionId] = ( 176 | (newLossPenalty * amount) 177 | + (currLossPenalty * user_deposits) 178 | ) / (user_deposits + amount); 179 | } 180 | 181 | // Transfer the token to this contract 182 | IERC20(depositToken).transferFrom(msg.sender, address(this), amount); 183 | 184 | // Update the user's deposit amount and total session deposits 185 | deposits[msg.sender][sessionId] += amount; 186 | totalDeposits[sessionId] += amount; 187 | } 188 | 189 | /// @notice Withdraws a deposit token from a session 190 | /// @dev Only permitted when the session is over 191 | /// @param amount The amount of the deposit token to withdraw 192 | function withdraw(uint256 amount) public { 193 | // Read Calldata Immutables 194 | uint256 sessionId = readSessionId(); 195 | uint64 allocationStart = readAllocationStart(); 196 | uint64 allocationEnd = readAllocationEnd(); 197 | uint64 mintingStart = readMintingStart(); 198 | uint64 mintingEnd = readMintingEnd(); 199 | address depositToken = readDepositToken(); 200 | uint8 rolloverOption = readRolloverOption(); 201 | 202 | // MSTORE timestamp is cheaper than double calls 203 | uint256 timestamp = block.timestamp; 204 | 205 | // Allows a user to withdraw deposits if session ends 206 | if (timestamp < mintingEnd || rolloverOption != 3) { 207 | revert NonAllocation(timestamp, allocationStart, allocationEnd); 208 | } 209 | 210 | // Get the loss penalty 211 | uint256 finalLossPenalty = lossPenalty[msg.sender][sessionId]; 212 | 213 | // Make sure the user has enough deposits to mint at least one, otherwise forfeit loss penalty 214 | uint256 totalUserDeposits = deposits[msg.sender][sessionId]; 215 | uint256 finalPrice = resultPrice[sessionId]; 216 | if (totalUserDeposits < finalPrice) { 217 | finalLossPenalty = 0; 218 | } 219 | 220 | // Update the user's deposit amount and total session deposits 221 | // This will revert on underflow so no need to check amount 222 | deposits[msg.sender][sessionId] -= amount; 223 | totalDeposits[sessionId] -= amount; 224 | 225 | // Transfer the token to this contract 226 | IERC20(depositToken).transfer(msg.sender, amount - ((finalLossPenalty * amount) / YAD)); 227 | } 228 | 229 | //////////////////////////////////////////////////// 230 | /// SESSION MINTING PERIOD /// 231 | //////////////////////////////////////////////////// 232 | 233 | /// @notice Mints tokens during minting period 234 | /// @param amount The amount of deposits to mint with 235 | function mint(uint256 amount) public { 236 | // Read Calldata Immutables 237 | address token = readToken(); 238 | address coordinator = readCoordinator(); 239 | uint256 sessionId = readSessionId(); 240 | uint64 mintingStart = readMintingStart(); 241 | uint64 mintingEnd = readMintingEnd(); 242 | address depositToken = readDepositToken(); 243 | uint256 maxMintingAmount = readMaxMintingAmount(); 244 | uint256 minPrice = readMinPrice(); 245 | address twamFactory = readTwamFactoryAddress(); 246 | 247 | // MSTORE timestamp is cheaper than double calls 248 | uint256 timestamp = block.timestamp; 249 | 250 | // Make sure the session is in the minting period 251 | if (timestamp > mintingEnd || timestamp < mintingStart) { 252 | revert NonMinting(timestamp, mintingStart, mintingEnd); 253 | } 254 | 255 | // Cache the result price 256 | if(resultPrice[sessionId] == 0) { 257 | // incur an additional SLOAD since this branch occurs once 258 | resultPrice[sessionId] = totalDeposits[sessionId] / maxMintingAmount; 259 | } 260 | 261 | // Calculate the mint price 262 | uint256 mintPrice = resultPrice[sessionId]; 263 | if(mintPrice < minPrice) mintPrice = minPrice; 264 | 265 | // Validate sender deposits and amount 266 | if (deposits[msg.sender][sessionId] < amount || amount < mintPrice) { 267 | // incur the additional SLOAD at the cost of a failed tx 268 | revert InsufficientDesposits(msg.sender, deposits[msg.sender][sessionId], amount); 269 | } 270 | 271 | // Get the next token Id to mint 272 | uint256 nextTokenToMint = nextMintId[sessionId]; 273 | 274 | // Reverts on underflow 275 | uint256 numberToMint = amount / mintPrice; 276 | 277 | // Reduce deposits 278 | deposits[msg.sender][sessionId] -= numberToMint * mintPrice; 279 | totalDeposits[sessionId] -= numberToMint * mintPrice; 280 | 281 | // Update the next id to mint 282 | nextMintId[sessionId] += numberToMint; 283 | 284 | // Mint 285 | for(uint256 i = nextTokenToMint; i < nextTokenToMint + numberToMint; i++) { 286 | IERC721(token).safeTransferFrom(twamFactory, msg.sender, i); 287 | } 288 | 289 | // Only give rewards to coordinator once the ERC721 Tokens are transferred 290 | rewards[coordinator][depositToken] += numberToMint * mintPrice; 291 | } 292 | 293 | /// @notice Allows a user to forgo their mint allocation 294 | /// @param amount The amount of deposits to withdraw 295 | function forgo(uint256 amount) public { 296 | // Read Calldata Immutables 297 | uint256 sessionId = readSessionId(); 298 | uint64 mintingStart = readMintingStart(); 299 | uint64 mintingEnd = readMintingEnd(); 300 | address depositToken = readDepositToken(); 301 | uint256 maxMintingAmount = readMaxMintingAmount(); 302 | 303 | // MSTORE timestamp is cheaper than double calls 304 | uint256 timestamp = block.timestamp; 305 | 306 | // Make sure the session is in the minting period 307 | if (timestamp > mintingEnd || timestamp < mintingStart) { 308 | revert NonMinting(timestamp, mintingStart, mintingEnd); 309 | } 310 | 311 | // Cache the result price 312 | if(resultPrice[sessionId] == 0) { 313 | // incur an additional SLOAD since this branch occurs once 314 | resultPrice[sessionId] = totalDeposits[sessionId] / maxMintingAmount; 315 | } 316 | 317 | // Get the loss penalty 318 | uint256 finalLossPenalty = lossPenalty[msg.sender][sessionId]; 319 | 320 | // Make sure the user has enough deposits to mint at least one, otherwise forfeit loss penalty 321 | uint256 totalUserDeposits = deposits[msg.sender][sessionId]; 322 | uint256 finalPrice = resultPrice[sessionId]; 323 | if (totalUserDeposits < finalPrice) { 324 | finalLossPenalty = 0; 325 | } 326 | 327 | // Update the user's deposit amount and total session deposits 328 | // This will revert on underflow so no need to check amount 329 | deposits[msg.sender][sessionId] -= amount; 330 | totalDeposits[sessionId] -= amount; 331 | 332 | // Transfer the token to this contract 333 | IERC20(depositToken).transfer(msg.sender, amount - ((finalLossPenalty * amount) / YAD)); 334 | } 335 | 336 | //////////////////////////////////////////////////// 337 | /// LOSS PENALTY /// 338 | //////////////////////////////////////////////////// 339 | 340 | /// @notice Calculates the Loss Penalty for a depositor 341 | /// @param amount The amount of `depositToken` 342 | /// @return penalty A fixed-point uint256 representing the loss penalty 343 | function simulateLossPenalty( 344 | uint256 amount, 345 | uint64 allocStart, 346 | uint64 allocEnd, 347 | uint256 timestamp 348 | ) public view returns(uint256 penalty) { 349 | // Calculate log of ceiling 350 | /// @dev end - 1, requires a manual check if allocEnd == block.timestamp, penalty = 1 351 | uint256 r = log2(YAD) / log2((allocEnd - 1) - allocStart); 352 | penalty = (timestamp - allocStart) ** r; 353 | } 354 | 355 | /// @dev Calculates the log base-2 using < 700 gas 356 | function log2(uint256 x) internal view returns (uint256 y){ 357 | assembly { 358 | let arg := x 359 | x := sub(x,1) 360 | x := or(x, div(x, 0x02)) 361 | x := or(x, div(x, 0x04)) 362 | x := or(x, div(x, 0x10)) 363 | x := or(x, div(x, 0x100)) 364 | x := or(x, div(x, 0x10000)) 365 | x := or(x, div(x, 0x100000000)) 366 | x := or(x, div(x, 0x10000000000000000)) 367 | x := or(x, div(x, 0x100000000000000000000000000000000)) 368 | x := add(x, 1) 369 | let m := mload(0x40) 370 | mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) 371 | mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) 372 | mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) 373 | mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) 374 | mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) 375 | mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) 376 | mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) 377 | mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) 378 | mstore(0x40, add(m, 0x100)) 379 | let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff 380 | let shift := 0x100000000000000000000000000000000000000000000000000000000000000 381 | let a := div(mul(x, magic), shift) 382 | y := div(mload(add(m,sub(255,a))), shift) 383 | y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) 384 | } 385 | } 386 | 387 | 388 | //////////////////////////////////////////////////// 389 | /// READ SESSION PARAMETERS /// 390 | //////////////////////////////////////////////////// 391 | 392 | /// @notice Reads the session ERC721 Token 393 | function readToken() public pure returns(address) { 394 | return _getArgAddress(0); 395 | } 396 | 397 | /// @notice Reads the Session Coordinator 398 | function readCoordinator() public pure returns(address) { 399 | return _getArgAddress(20); 400 | } 401 | 402 | /// @notice Reads the Session Allocation Period Start Timestamp 403 | function readAllocationStart() public pure returns(uint64) { 404 | return _getArgUint64(40); 405 | } 406 | 407 | /// @notice Reads the Session Allocation Period End Timestamp 408 | function readAllocationEnd() public pure returns(uint64) { 409 | return _getArgUint64(48); 410 | } 411 | 412 | /// @notice Reads the Session Minting Period Start Timestamp 413 | function readMintingStart() public pure returns(uint64) { 414 | return _getArgUint64(56); 415 | } 416 | 417 | /// @notice Reads the Session Minting Period End Timestamp 418 | function readMintingEnd() public pure returns(uint64) { 419 | return _getArgUint64(64); 420 | } 421 | 422 | /// @notice Reads the Session Minimum ERC721 Token Sale Price 423 | function readMinPrice() public pure returns(uint256) { 424 | return _getArgUint256(72); 425 | } 426 | 427 | /// @notice Reads the Session Maximum Number of Available Tokens to Mint 428 | function readMaxMintingAmount() public pure returns(uint256) { 429 | return _getArgUint256(104); 430 | } 431 | 432 | /// @notice Reads the Session Deposit ERC20 Token 433 | function readDepositToken() public pure returns(address) { 434 | return _getArgAddress(136); 435 | } 436 | 437 | /// @notice Reads the Session Rollover Option 438 | function readRolloverOption() public pure returns(uint8) { 439 | return _getArgUint8(156); 440 | } 441 | 442 | /// @notice Reads the Session ID 443 | function readSessionId() public pure returns(uint256) { 444 | return _getArgUint256(157); 445 | } 446 | 447 | /// @notice Reads the Twam Factory Address 448 | function readTwamFactoryAddress() public pure returns(address) { 449 | return _getArgAddress(189); 450 | } 451 | } 452 | -------------------------------------------------------------------------------- /src/test/TwamBase.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-only 2 | pragma solidity 0.8.11; 3 | 4 | 5 | import {stdCheats, stdError} from "@std/stdlib.sol"; 6 | import {Vm} from "@std/Vm.sol"; 7 | 8 | import {MockERC20} from "@solmate/test/utils/mocks/MockERC20.sol"; 9 | import {MockERC721} from "@solmate/test/utils/mocks/MockERC721.sol"; 10 | import {SafeCastLib} from "@solmate/utils/SafeCastLib.sol"; 11 | 12 | import {DSTestPlus} from "./utils/DSTestPlus.sol"; 13 | import {TwamBase} from "../TwamBase.sol"; 14 | import {TwamFactory} from "../TwamFactory.sol"; 15 | 16 | /// @dev DSTestPlus inherits stdCheats 17 | contract TwamBaseTest is DSTestPlus { 18 | 19 | /// @dev Contracts 20 | TwamBase public twamBase; // Twam Base (Clone) 21 | TwamFactory public twamFactory; // Twam Factory 22 | MockERC721 public badMockERC721; // Mock Invalid ERC721 Token 23 | TwamBase public exampleClone = new TwamBase(); 24 | 25 | /// @dev Twam Session Arguments 26 | MockERC721 public mockToken; // Mock ERC721 Token 27 | address public constant COORDINATOR = 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B; 28 | uint64 public recordedTimestamp; 29 | uint64 public allocationStart; 30 | uint64 public allocationEnd; 31 | uint64 public mintingStart; 32 | uint64 public mintingEnd; 33 | uint256 public minPrice; 34 | MockERC20 public depositToken; // Mock ERC20 Deposit Token 35 | uint256 public constant TOKEN_SUPPLY = 10_000; 36 | uint256 public maxMintingAmount = TOKEN_SUPPLY; 37 | uint8 public rolloverOption; 38 | 39 | /// @notice Testing suite precursors 40 | function setUp() public { 41 | twamFactory = new TwamFactory(exampleClone); 42 | 43 | // Creat Mock Tokens 44 | depositToken = new MockERC20("Token", "TKN", 18); 45 | mockToken = new MockERC721("Token", "TKN"); 46 | badMockERC721 = new MockERC721("Token", "TKN"); 47 | 48 | // Create the TWAM Session 49 | uint64 t = SafeCastLib.safeCastTo64(block.timestamp); 50 | recordedTimestamp = t; 51 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 52 | mockToken.mint(COORDINATOR, 0); 53 | mockToken.approve(COORDINATOR, 0); 54 | mockToken.safeTransferFrom( 55 | COORDINATOR, // from 56 | address(twamFactory), // to 57 | 0, // id 58 | abi.encode(address(mockToken)) // data 59 | ); 60 | for(uint256 i = 1; i < TOKEN_SUPPLY; i++) { 61 | mockToken.mint(address(twamFactory), i); 62 | } 63 | twamBase = twamFactory.createTwam( 64 | address(mockToken), // token 65 | COORDINATOR, // coordinator 66 | allocationStart = t + 10, // allocationStart, 67 | allocationEnd = t + 15, // allocationEnd, 68 | mintingStart = t + 20, // mintingStart, 69 | mintingEnd = t + 25, // mintingEnd, 70 | minPrice = 1, // minPrice, 71 | address(depositToken), // depositToken 72 | TOKEN_SUPPLY, // maxMintingAmount, 73 | rolloverOption = 1 // rolloverOption 74 | ); 75 | vm.stopPrank(); 76 | } 77 | 78 | //////////////////////////////////////////////////// 79 | /// SESSION MANAGEMENT LOGIC /// 80 | //////////////////////////////////////////////////// 81 | 82 | /// @notice Tests rolling over a session 83 | function testRollover() public { 84 | vm.warp(recordedTimestamp); 85 | 86 | // Expect Revert when not called from the coordinator context 87 | vm.expectRevert( 88 | abi.encodeWithSignature( 89 | "InvalidCoordinator(address,address)", 90 | address(this), 91 | COORDINATOR 92 | ) 93 | ); 94 | twamBase.rollover(); 95 | 96 | // Hoax from the COORDINATOR context 97 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 98 | 99 | // Expect Revert when the mint isn't over 100 | vm.expectRevert( 101 | abi.encodeWithSignature( 102 | "MintingNotOver(uint256,uint64)", 103 | recordedTimestamp, 104 | mintingEnd 105 | ) 106 | ); 107 | twamBase.rollover(); 108 | 109 | // Roll the block height 110 | vm.warp(mintingEnd); 111 | 112 | // The rollover should succeed now that the minting period is over 113 | twamBase.rollover(); 114 | 115 | vm.stopPrank(); 116 | } 117 | 118 | /// @notice Coordinators are able to withdraw their rewards 119 | function testWithdrawRewards() public { 120 | // Jump to allocation period 121 | vm.warp(allocationStart); 122 | 123 | // Create Mock Users 124 | address firstUser = address(1); 125 | address secondUser = address(2); 126 | 127 | // Give them depositToken balances 128 | depositToken.mint(firstUser, 1e18); 129 | depositToken.mint(secondUser, 1e18); 130 | 131 | // Mock first user deposits 132 | startHoax(firstUser, firstUser, type(uint256).max); 133 | depositToken.approve(address(twamBase), 1e18); // Approve the TWAM to transfer the depositToken 134 | twamBase.deposit(TOKEN_SUPPLY); 135 | assert(depositToken.balanceOf(address(twamBase)) == TOKEN_SUPPLY); 136 | vm.stopPrank(); 137 | 138 | // Mock second user deposits 139 | startHoax(secondUser, secondUser, type(uint256).max); 140 | depositToken.approve(address(twamBase), 1e18); // Approve the TWAM to transfer the depositToken 141 | twamBase.deposit(TOKEN_SUPPLY); 142 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 143 | vm.stopPrank(); 144 | 145 | // Jump to minting period 146 | vm.warp(mintingStart); 147 | 148 | // Mock first user mints 149 | startHoax(firstUser, firstUser, type(uint256).max); 150 | twamBase.mint(TOKEN_SUPPLY); 151 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY / 2); 152 | assert(mockToken.balanceOf(address(firstUser)) == TOKEN_SUPPLY / 2); 153 | assert(twamBase.rewards(COORDINATOR, address(depositToken)) == TOKEN_SUPPLY); 154 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 155 | vm.stopPrank(); 156 | 157 | // Mock second user mints 158 | startHoax(secondUser, secondUser, type(uint256).max); 159 | twamBase.mint(TOKEN_SUPPLY); 160 | assert(mockToken.balanceOf(address(twamFactory)) == 0); 161 | assert(mockToken.balanceOf(address(secondUser)) == TOKEN_SUPPLY / 2); 162 | assert(twamBase.rewards(COORDINATOR, address(depositToken)) == 2 * TOKEN_SUPPLY); 163 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 164 | vm.stopPrank(); 165 | 166 | // Jump to post-mint 167 | vm.warp(mintingEnd); 168 | 169 | // Try to withdraw rewards 170 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 171 | assert(depositToken.balanceOf(COORDINATOR) == 0); 172 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 173 | assert(twamBase.rewards(COORDINATOR, address(depositToken)) == 2 * TOKEN_SUPPLY); 174 | twamBase.withdrawRewards(); 175 | assert(depositToken.balanceOf(COORDINATOR) == 2 * TOKEN_SUPPLY); 176 | vm.stopPrank(); 177 | } 178 | 179 | //////////////////////////////////////////////////// 180 | /// SESSION ALLOCATION PERIOD /// 181 | //////////////////////////////////////////////////// 182 | 183 | /// @notice Test deposits 184 | function testDeposit() public { 185 | // Jump to after the allocation period 186 | vm.warp(allocationEnd + 1); 187 | 188 | // Expect Revert when we are after the allocation period 189 | vm.expectRevert( 190 | abi.encodeWithSignature( 191 | "NonAllocation(uint256,uint64,uint64)", 192 | allocationEnd + 1, 193 | allocationStart, 194 | allocationEnd 195 | ) 196 | ); 197 | twamBase.deposit(TOKEN_SUPPLY); 198 | 199 | // Reset to before the allocation period 200 | vm.warp(allocationStart - 1); 201 | 202 | // Expect Revert when we are before the allocation period 203 | vm.expectRevert( 204 | abi.encodeWithSignature( 205 | "NonAllocation(uint256,uint64,uint64)", 206 | allocationStart - 1, 207 | allocationStart, 208 | allocationEnd 209 | ) 210 | ); 211 | twamBase.deposit(TOKEN_SUPPLY); 212 | 213 | // Jump to allocation period 214 | vm.warp(allocationStart); 215 | 216 | // Create Mock Users 217 | address firstUser = address(1); 218 | address secondUser = address(2); 219 | 220 | // Give them depositToken balances 221 | depositToken.mint(firstUser, 1e18); 222 | depositToken.mint(secondUser, 1e18); 223 | 224 | // Mock first user deposits 225 | startHoax(firstUser, firstUser, type(uint256).max); 226 | depositToken.approve(address(twamBase), 1e18); // Approve the twamBase to transfer the depositToken 227 | twamBase.deposit(TOKEN_SUPPLY); 228 | assert(depositToken.balanceOf(address(twamBase)) == TOKEN_SUPPLY); 229 | vm.stopPrank(); 230 | 231 | // Mock second user deposits 232 | startHoax(secondUser, secondUser, type(uint256).max); 233 | depositToken.approve(address(twamBase), 1e18); // Approve the twamBase to transfer the depositToken 234 | twamBase.deposit(TOKEN_SUPPLY); 235 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 236 | vm.stopPrank(); 237 | } 238 | 239 | /// @notice Tests users can withdraw after minting ends when session rollover = 3 240 | function testWithdrawals() public { 241 | // Replicate Base Variables 242 | TwamFactory twamFactory2 = new TwamFactory(exampleClone); 243 | 244 | // Creat Mock Tokens 245 | MockERC20 depositToken2 = new MockERC20("Token", "TKN", 18); 246 | MockERC721 mockToken2 = new MockERC721("Token", "TKN"); 247 | 248 | // Create a rollover=3 TWAM Session 249 | uint64 t = SafeCastLib.safeCastTo64(block.timestamp); 250 | recordedTimestamp = t; 251 | startHoax(COORDINATOR, COORDINATOR, type(uint256).max); 252 | mockToken2.mint(COORDINATOR, 0); 253 | mockToken2.approve(COORDINATOR, 0); 254 | mockToken2.safeTransferFrom( 255 | COORDINATOR, // from 256 | address(twamFactory2), // to 257 | 0, // id 258 | abi.encode(address(mockToken2)) // data 259 | ); 260 | for(uint256 i = 1; i < TOKEN_SUPPLY; i++) { 261 | mockToken2.mint(address(twamFactory2), i); 262 | } 263 | TwamBase twamBase2 = twamFactory2.createTwam( 264 | address(mockToken2), // token 265 | COORDINATOR, // coordinator 266 | t + 10, // allocationStart, 267 | t + 15, // allocationEnd, 268 | t + 20, // mintingStart, 269 | t + 25, // mintingEnd, 270 | 1, // minPrice, 271 | address(depositToken2), // depositToken 272 | TOKEN_SUPPLY, // maxMintingAmount, 273 | 3 // rolloverOption 274 | ); 275 | vm.stopPrank(); 276 | 277 | // Jump to allocation period 278 | vm.warp(t + 10); 279 | 280 | // Create Mock Users 281 | address firstUser = address(1); 282 | depositToken2.mint(firstUser, 1e18); 283 | 284 | // Mock user deposits 285 | startHoax(firstUser, firstUser, type(uint256).max); 286 | depositToken2.approve(address(twamBase2), 1e18); // Approve the twamBase2 to transfer the depositToken2 287 | twamBase2.deposit(TOKEN_SUPPLY); 288 | assert(depositToken2.balanceOf(address(twamBase2)) == TOKEN_SUPPLY); 289 | vm.stopPrank(); 290 | 291 | // Jump to after the mint period 292 | vm.warp(t + 26); 293 | 294 | // Mock user withdrawal 295 | startHoax(firstUser, firstUser, type(uint256).max); 296 | assert(depositToken2.balanceOf(address(twamBase2)) == TOKEN_SUPPLY); 297 | twamBase2.withdraw(TOKEN_SUPPLY); 298 | assert(depositToken2.balanceOf(address(twamBase2)) == 0); 299 | vm.stopPrank(); 300 | } 301 | 302 | //////////////////////////////////////////////////// 303 | /// SESSION MINTING PERIOD /// 304 | //////////////////////////////////////////////////// 305 | 306 | /// @notice Tests minting period 307 | function testMints() public { 308 | // Jump to allocation period 309 | vm.warp(allocationStart); 310 | 311 | // Create Users 312 | address firstUser = address(1); 313 | address secondUser = address(2); 314 | depositToken.mint(firstUser, 1e18); 315 | depositToken.mint(secondUser, 1e18); 316 | 317 | // Users Deposit 318 | startHoax(firstUser, firstUser, type(uint256).max); 319 | depositToken.approve(address(twamBase), 1e18); 320 | twamBase.deposit(TOKEN_SUPPLY); 321 | vm.stopPrank(); 322 | startHoax(secondUser, secondUser, type(uint256).max); 323 | depositToken.approve(address(twamBase), 1e18); 324 | twamBase.deposit(TOKEN_SUPPLY); 325 | 326 | // User can't mint before minting period starts 327 | vm.expectRevert( 328 | abi.encodeWithSignature( 329 | "NonMinting(uint256,uint64,uint64)", 330 | allocationStart, 331 | mintingStart, 332 | mintingEnd 333 | )); 334 | twamBase.mint(TOKEN_SUPPLY); 335 | 336 | vm.stopPrank(); 337 | 338 | // Jump to minting period 339 | vm.warp(mintingStart); 340 | 341 | // Mock first user mints 342 | startHoax(firstUser, firstUser, type(uint256).max); 343 | 344 | // User shouldn't be able to mint more than their deposits 345 | vm.expectRevert( 346 | abi.encodeWithSignature( 347 | "InsufficientDesposits(address,uint256,uint256)", 348 | firstUser, 349 | TOKEN_SUPPLY, 350 | 2 * TOKEN_SUPPLY 351 | ) 352 | ); 353 | twamBase.mint(2 * TOKEN_SUPPLY); 354 | 355 | // Then they should successfully be able to mint 356 | twamBase.mint(TOKEN_SUPPLY); 357 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY / 2); 358 | assert(mockToken.balanceOf(address(firstUser)) == TOKEN_SUPPLY / 2); 359 | assert(twamBase.rewards(COORDINATOR, address(depositToken)) == TOKEN_SUPPLY); 360 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 361 | 362 | // Check that the session `resultPrice` is correct 363 | assert(twamBase.resultPrice(1) == 2); 364 | vm.stopPrank(); 365 | 366 | // Mock second user mints 367 | startHoax(secondUser, secondUser, type(uint256).max); 368 | 369 | // User shouldn't be able to mint more than their deposits 370 | vm.expectRevert(abi.encodeWithSignature( 371 | "InsufficientDesposits(address,uint256,uint256)", 372 | secondUser, TOKEN_SUPPLY, 2 * TOKEN_SUPPLY 373 | )); 374 | twamBase.mint(2 * TOKEN_SUPPLY); 375 | 376 | twamBase.mint(TOKEN_SUPPLY); 377 | assert(mockToken.balanceOf(address(twamFactory)) == 0); 378 | assert(mockToken.balanceOf(address(secondUser)) == TOKEN_SUPPLY / 2); 379 | assert(twamBase.rewards(COORDINATOR, address(depositToken)) == 2 * TOKEN_SUPPLY); 380 | assert(depositToken.balanceOf(address(twamBase)) == 2 * TOKEN_SUPPLY); 381 | 382 | // Check that the session `resultPrice` is still correct 383 | assert(twamBase.resultPrice(1) == 2); 384 | 385 | vm.stopPrank(); 386 | } 387 | 388 | /// @notice Tests forgoing a mint 389 | function testForgo() public { 390 | // Jump to allocation period 391 | vm.warp(allocationStart); 392 | 393 | // Create Users 394 | address firstUser = address(1); 395 | address secondUser = address(2); 396 | depositToken.mint(firstUser, 1e18); 397 | depositToken.mint(secondUser, 1e18); 398 | 399 | // Users Deposit 400 | startHoax(firstUser, firstUser, type(uint256).max); 401 | depositToken.approve(address(twamBase), 1e18); 402 | twamBase.deposit(TOKEN_SUPPLY); 403 | vm.stopPrank(); 404 | startHoax(secondUser, secondUser, type(uint256).max); 405 | depositToken.approve(address(twamBase), 1e18); 406 | twamBase.deposit(TOKEN_SUPPLY); 407 | 408 | // User can't forgo before minting period starts 409 | vm.expectRevert(abi.encodeWithSignature( 410 | "NonMinting(uint256,uint64,uint64)", 411 | allocationStart, 412 | mintingStart, 413 | mintingEnd 414 | )); 415 | twamBase.forgo(TOKEN_SUPPLY); 416 | 417 | vm.stopPrank(); 418 | 419 | // Jump to minting period 420 | vm.warp(mintingStart); 421 | 422 | // Mock first user forgos 423 | startHoax(firstUser, firstUser, type(uint256).max); 424 | 425 | // Then they should successfully be able to forgo 426 | twamBase.forgo(TOKEN_SUPPLY); 427 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY); 428 | assert(mockToken.balanceOf(address(firstUser)) == 0); 429 | assert(depositToken.balanceOf(address(twamBase)) == TOKEN_SUPPLY); 430 | 431 | // Check that the session `resultPrice` is correct 432 | assert(twamBase.resultPrice(1) == 2); 433 | vm.stopPrank(); 434 | 435 | // Mock second user forgos 436 | startHoax(secondUser, secondUser, type(uint256).max); 437 | 438 | twamBase.forgo(TOKEN_SUPPLY); 439 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY); 440 | assert(mockToken.balanceOf(address(secondUser)) == 0); 441 | assert(depositToken.balanceOf(address(twamBase)) == 0); 442 | 443 | // Check that the session `resultPrice` is still correct 444 | assert(twamBase.resultPrice(1) == 2); 445 | vm.stopPrank(); 446 | } 447 | 448 | /// @notice Tests forgoing a mint with a loss penalty 449 | function testForgoWithLossPenalty() public { 450 | // Jump to the middle of the allocation period 451 | uint64 nearEndAllocation = allocationEnd - 1; 452 | vm.warp(nearEndAllocation); 453 | 454 | // Create Users 455 | address firstUser = address(1); 456 | address secondUser = address(2); 457 | depositToken.mint(firstUser, TOKEN_SUPPLY); 458 | depositToken.mint(secondUser, TOKEN_SUPPLY); 459 | 460 | // Users Deposit 461 | startHoax(firstUser, firstUser, type(uint256).max); 462 | depositToken.approve(address(twamBase), TOKEN_SUPPLY); 463 | twamBase.deposit(TOKEN_SUPPLY); 464 | vm.stopPrank(); 465 | startHoax(secondUser, secondUser, type(uint256).max); 466 | depositToken.approve(address(twamBase), TOKEN_SUPPLY); 467 | twamBase.deposit(TOKEN_SUPPLY); 468 | 469 | // User can't forgo before minting period starts 470 | vm.expectRevert(abi.encodeWithSignature( 471 | "NonMinting(uint256,uint64,uint64)", 472 | nearEndAllocation, 473 | mintingStart, 474 | mintingEnd 475 | )); 476 | twamBase.forgo(TOKEN_SUPPLY); 477 | 478 | vm.stopPrank(); 479 | 480 | // Jump to minting period 481 | vm.warp(mintingStart); 482 | 483 | // Mock first user forgos 484 | startHoax(firstUser, firstUser, type(uint256).max); 485 | 486 | // Then they should successfully be able to forgo 487 | twamBase.forgo(TOKEN_SUPPLY); 488 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY); 489 | assert(mockToken.balanceOf(address(firstUser)) == 0); 490 | 491 | // Check that the loss penalty came into effect 492 | assert(depositToken.balanceOf(firstUser) < TOKEN_SUPPLY); 493 | assert(depositToken.balanceOf(address(twamBase)) >= TOKEN_SUPPLY); 494 | 495 | // Check that the session `resultPrice` is correct 496 | assert(twamBase.resultPrice(1) == 2); 497 | vm.stopPrank(); 498 | 499 | // Mock second user forgos 500 | startHoax(secondUser, secondUser, type(uint256).max); 501 | 502 | twamBase.forgo(TOKEN_SUPPLY); 503 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY); 504 | assert(mockToken.balanceOf(address(secondUser)) == 0); 505 | 506 | // Check the loss penalty 507 | assert(depositToken.balanceOf(secondUser) < TOKEN_SUPPLY); 508 | assert(depositToken.balanceOf(address(twamBase)) >= 0); 509 | 510 | // Check that the session `resultPrice` is still correct 511 | assert(twamBase.resultPrice(1) == 2); 512 | vm.stopPrank(); 513 | } 514 | 515 | /// @notice Tests forgoing a full loss penalty 516 | function testForgoWithFullLossPenalty() public { 517 | // Jump to the end of the allocation period 518 | vm.warp(allocationEnd); 519 | 520 | // Create Users 521 | address firstUser = address(1); 522 | address secondUser = address(2); 523 | depositToken.mint(firstUser, TOKEN_SUPPLY); 524 | depositToken.mint(secondUser, TOKEN_SUPPLY); 525 | 526 | // Users Deposit 527 | startHoax(firstUser, firstUser, type(uint256).max); 528 | depositToken.approve(address(twamBase), TOKEN_SUPPLY); 529 | twamBase.deposit(TOKEN_SUPPLY); 530 | vm.stopPrank(); 531 | startHoax(secondUser, secondUser, type(uint256).max); 532 | depositToken.approve(address(twamBase), TOKEN_SUPPLY); 533 | twamBase.deposit(TOKEN_SUPPLY); 534 | 535 | // User can't forgo before minting period starts 536 | vm.expectRevert(abi.encodeWithSignature( 537 | "NonMinting(uint256,uint64,uint64)", 538 | allocationEnd, 539 | mintingStart, 540 | mintingEnd 541 | )); 542 | twamBase.forgo(TOKEN_SUPPLY); 543 | 544 | vm.stopPrank(); 545 | 546 | // Jump to minting period 547 | vm.warp(mintingStart); 548 | 549 | // Mock first user forgos 550 | startHoax(firstUser, firstUser, type(uint256).max); 551 | 552 | // Then they should successfully be able to forgo 553 | twamBase.forgo(TOKEN_SUPPLY); 554 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY); 555 | assert(mockToken.balanceOf(address(firstUser)) == 0); 556 | 557 | // Check that the loss penalty came into effect 558 | assert(depositToken.balanceOf(firstUser) == 0); 559 | assert(depositToken.balanceOf(address(twamBase)) >= TOKEN_SUPPLY); 560 | 561 | // Check that the session `resultPrice` is correct 562 | assert(twamBase.resultPrice(1) == 2); 563 | vm.stopPrank(); 564 | 565 | // Mock second user forgos 566 | startHoax(secondUser, secondUser, type(uint256).max); 567 | 568 | twamBase.forgo(TOKEN_SUPPLY); 569 | assert(mockToken.balanceOf(address(twamFactory)) == TOKEN_SUPPLY); 570 | assert(mockToken.balanceOf(address(secondUser)) == 0); 571 | 572 | // Check the loss penalty 573 | assert(depositToken.balanceOf(secondUser) == 0); 574 | assert(depositToken.balanceOf(address(twamBase)) >= 0); 575 | 576 | // Check that the session `resultPrice` is still correct 577 | assert(twamBase.resultPrice(1) == 2); 578 | vm.stopPrank(); 579 | } 580 | 581 | //////////////////////////////////////////////////// 582 | /// READ SESSION PARAMETERS /// 583 | //////////////////////////////////////////////////// 584 | 585 | /// @notice Tests reading the ERC721 Token from Immutable Args 586 | function testReadToken() public { 587 | address read_token = twamBase.readToken(); 588 | assertEq(read_token, address(mockToken)); 589 | } 590 | 591 | /// @notice Tests reading the Coordinator from Immutable Args 592 | function testReadCoordinator() public { 593 | address read_coordinator = twamBase.readCoordinator(); 594 | assertEq(read_coordinator, COORDINATOR); 595 | } 596 | 597 | /// @notice Tests reading the Allocation Start from Immutable Args 598 | function testReadAllocationStart() public { 599 | uint64 read_alloc_start = twamBase.readAllocationStart(); 600 | assert(read_alloc_start == allocationStart); 601 | } 602 | 603 | /// @notice Tests reading the Allocation End from Immutable Args 604 | function testReadAllocationEnd() public { 605 | uint64 read_alloc_end = twamBase.readAllocationEnd(); 606 | assert(read_alloc_end == allocationEnd); 607 | } 608 | 609 | /// @notice Tests reading the Minting Start from Immutable Args 610 | function testReadMintingStart() public { 611 | uint64 read_minting_start = twamBase.readMintingStart(); 612 | assert(read_minting_start == mintingStart); 613 | } 614 | 615 | /// @notice Tests reading the Minting End from Immutable Args 616 | function testReadMintingEnd() public { 617 | uint64 read_minting_end = twamBase.readMintingEnd(); 618 | assert(read_minting_end == mintingEnd); 619 | } 620 | 621 | /// @notice Tests reading the Min Price from Immutable Args 622 | function testReadMinPrice() public { 623 | uint256 read_min_price = twamBase.readMinPrice(); 624 | assert(read_min_price == minPrice); 625 | } 626 | 627 | /// @notice Tests reading the Maximum Minting Amount from Immutable Args 628 | function testReadMaxMintingAmount() public { 629 | uint256 read_max_minting_amount = twamBase.readMaxMintingAmount(); 630 | assert(read_max_minting_amount == maxMintingAmount); 631 | } 632 | 633 | /// @notice Tests reading the Deposit Token from Immutable Args 634 | function testReadDepositToken() public { 635 | address read_deposit_token = twamBase.readDepositToken(); 636 | assert(read_deposit_token == address(depositToken)); 637 | } 638 | 639 | /// @notice Tests reading the Rollover Option from Immutable Args 640 | function testReadRolloverOption() public { 641 | uint8 read_rollover_option = twamBase.readRolloverOption(); 642 | assert(read_rollover_option == rolloverOption); 643 | } 644 | 645 | /// @notice Tests reading the Session Id from Immutable Args 646 | function testReadSessionId() public { 647 | uint256 read_session_id = twamBase.readSessionId(); 648 | assert(read_session_id == 1); 649 | } 650 | 651 | /// @notice Tests reading the Twam Factory Address from Immutable Args 652 | function testReadTwamFactoryAddress() public { 653 | address read_twam_factory_addr = twamBase.readTwamFactoryAddress(); 654 | assert(read_twam_factory_addr == address(twamFactory)); 655 | } 656 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------