├── .gitignore ├── .idea ├── .gitignore ├── matic-exchange-contracts.iml ├── modules.xml └── vcs.xml ├── .npmignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── contracts ├── elk-core │ ├── CalculateElkPairHash.sol │ ├── ElkERC20.sol │ ├── ElkFactory.sol │ ├── ElkPair.sol │ ├── interfaces │ │ ├── IERC20.sol │ │ ├── IElkCallee.sol │ │ ├── IElkERC20.sol │ │ ├── IElkFactory.sol │ │ └── IElkPair.sol │ └── libraries │ │ ├── Math.sol │ │ ├── SafeMath.sol │ │ └── UQ112x112.sol ├── elk-lib │ └── libraries │ │ ├── AddressStringUtil.sol │ │ ├── Babylonian.sol │ │ ├── FixedPoint.sol │ │ ├── FullMath.sol │ │ ├── PairNamer.sol │ │ ├── SafeERC20Namer.sol │ │ └── TransferHelper.sol └── elk-periphery │ ├── ElkRouter.sol │ ├── interfaces │ ├── IERC20.sol │ ├── IElkRouter.sol │ └── IWETH.sol │ └── libraries │ ├── ElkLibrary.sol │ ├── SafeMath.sol │ └── UniswapV2OracleLibrary.sol ├── elk-interface.png ├── hardhat.config.js ├── package.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | contracts/TestERC20.sol 2 | contracts/WMATIC.sol 3 | scripts/ 4 | test/ 5 | cache/ 6 | node_modules/ 7 | artifacts/ 8 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | -------------------------------------------------------------------------------- /.idea/matic-exchange-contracts.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | contracts/TestERC20.sol 2 | contracts/WETH.sol 3 | scripts/ 4 | test/ 5 | cache/ 6 | node_modules/ 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [atom@github.com](mailto:atom@github.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: https://contributor-covenant.org 46 | [version]: https://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Elk.Finance 2 | 3 | :+1::tada: First off, thanks for taking the time to contribute! :tada::+1: 4 | 5 | The following is a set of guidelines for contributing to Elk.Finance and its packages, which are hosted in the [Elk Finance Organization](https://github.com/elkfinance) on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | #### Table Of Contents 8 | 9 | [Code of Conduct](#code-of-conduct) 10 | 11 | [I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question) 12 | 13 | [How Can I Contribute?](#how-can-i-contribute) 14 | * [Reporting Bugs](#reporting-bugs) 15 | * [Suggesting Enhancements](#suggesting-enhancements) 16 | * [Your First Code Contribution](#your-first-code-contribution) 17 | * [Pull Requests](#pull-requests) 18 | 19 | [Styleguides](#styleguides) 20 | * [Git Commit Messages](#git-commit-messages) 21 | * [JavaScript Styleguide](#javascript-styleguide) 22 | * [CoffeeScript Styleguide](#coffeescript-styleguide) 23 | * [Specs Styleguide](#specs-styleguide) 24 | * [Documentation Styleguide](#documentation-styleguide) 25 | 26 | [Additional Notes](#additional-notes) 27 | * [Issue and Pull Request Labels](#issue-and-pull-request-labels) 28 | 29 | ## Code of Conduct 30 | 31 | This project and everyone participating in it is governed by the [Elk.Finance Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [dev@elk.finance](mailto:dev@elk.finance). 32 | 33 | ## I don't want to read this whole thing I just have a question!!! 34 | 35 | > **Note:** Please don't file an issue to ask a question. You will get faster results by using the resources below. 36 | 37 | We have an official Telegram chat where the community can provide advice if you have questions. 38 | 39 | * [Telegram](https://t.me/elk-finance-chat) 40 | * [Elk FAQ](https://elk.finance/#faq) 41 | 42 | ## What should I know before I get started? 43 | 44 | ### Elk and Packages 45 | 46 | Elk is a large open-source project made up of seeral repositories. Elk is very modular. 47 | 48 | Here's a list of the main packages: 49 | 50 | * [exchange-contracts](https://github.com/elkfinance/exchange-contracts.git) - The core Elk Exchange contracts. 51 | * [sdk](https://github.com/elkfinance/sdk.git) - The Elk Finance SDK. 52 | * [tokenlists](https://github.com/elkfinance/tokenlists.git) - Lists of supported tokens. 53 | * [elkfinance.github.io](https://github.com/elkfinance/elkfinance.github.io.git) - The Elk.Finance website. 54 | * [liquidity-scores](https://github.com/elkfinance/liquidity-scores.git) - Liquidity score computations. 55 | 56 | ## How Can I Contribute? 57 | 58 | ### Reporting Bugs 59 | 60 | This section guides you through submitting a bug report for Elk. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:. 61 | 62 | Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). 63 | 64 | > **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. 65 | 66 | #### Before Submitting A Bug Report 67 | 68 | * **Check the [FAQs](https://docs.elk.finance)** for a list of common questions and problems. 69 | * **Determine which repository the problem should be reported in**. 70 | * **Perform a [cursory search](https://github.com/search?q=+is%3Aissue+user%3Aelk)** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one. 71 | 72 | #### How Do I Submit A (Good) Bug Report? 73 | 74 | Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your bug is related to, create an issue on that repository and provide the necessary information to reproduce the bug. 75 | 76 | Explain the problem and include additional details to help maintainers reproduce the problem: 77 | 78 | * **Use a clear and descriptive title** for the issue to identify the problem. 79 | * **Describe the exact steps which reproduce the problem** in as many details as possible. 80 | * **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). 81 | * **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. 82 | * **Explain which behavior you expected to see instead and why.** 83 | * **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 84 | 85 | Provide more context by answering these questions: 86 | 87 | * **Did the problem start happening recently** or was this always a problem? 88 | * **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens. 89 | 90 | Include details about your configuration and environment: 91 | 92 | * **What's the name and version of the OS you're using**? 93 | * **What's the name and version of the web browser you're using**? 94 | 95 | ### Suggesting Enhancements 96 | 97 | This section guides you through submitting an enhancement suggestion for Elk, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. 98 | 99 | Before creating enhancement suggestions, please check the [documentation](https://docs.elk.finance) and [roadmap](https://elk.finance/litepaper.html) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). 100 | 101 | #### Before Submitting An Enhancement Suggestion 102 | 103 | * **Determine which repository the enhancement should be suggested in.** 104 | * **Perform a [cursory search](https://github.com/search?q=+is%3Aissue+user%3Aelk)** to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. 105 | 106 | #### How Do I Submit A (Good) Enhancement Suggestion? 107 | 108 | Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined your enhancement suggestion is related to, create an issue on that repository and provide the following information: 109 | 110 | * **Use a clear and descriptive title** for the issue to identify the suggestion. 111 | * **Provide a step-by-step description of the suggested enhancement** in as many details as possible. 112 | * **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). 113 | * **Describe the current behavior** and **explain which behavior you expected to see instead** and why. 114 | * **Include screenshots and animated GIFs** which help you demonstrate the steps or point out the part of Elk which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 115 | * **Explain why this enhancement would be useful** to most Elk users. 116 | * **List some other text editors or applications where this enhancement exists.** 117 | 118 | ### Your First Code Contribution 119 | 120 | Unsure where to begin contributing to Elk? You can start by looking through these `beginner` and `help-wanted` issues: 121 | 122 | * [Beginner issues][beginner] - issues which should only require a few lines of code, and a test or two. 123 | * [Help wanted issues][help-wanted] - issues which should be a bit more involved than `beginner` issues. 124 | 125 | Both issue lists are sorted by total number of comments. While not perfect, number of comments is a reasonable proxy for impact a given change will have. 126 | 127 | 128 | ### Pull Requests 129 | 130 | The process described here has several goals: 131 | 132 | - Maintain Elk's quality 133 | - Fix problems that are important to users 134 | - Engage the community in working toward the best possible Elk 135 | - Enable a sustainable system for Elk's maintainers to review contributions 136 | 137 | ## Styleguides 138 | 139 | ### Git Commit Messages 140 | 141 | * Use the present tense ("Add feature" not "Added feature") 142 | * Use the imperative mood ("Move cursor to..." not "Moves cursor to...") 143 | * Limit the first line to 72 characters or less 144 | * Reference issues and pull requests liberally after the first line 145 | * When only changing documentation, include `[ci skip]` in the commit title 146 | * Consider starting the commit message with an applicable emoji: 147 | * :art: `:art:` when improving the format/structure of the code 148 | * :racehorse: `:racehorse:` when improving performance 149 | * :non-potable_water: `:non-potable_water:` when plugging memory leaks 150 | * :memo: `:memo:` when writing docs 151 | * :penguin: `:penguin:` when fixing something on Linux 152 | * :apple: `:apple:` when fixing something on macOS 153 | * :checkered_flag: `:checkered_flag:` when fixing something on Windows 154 | * :bug: `:bug:` when fixing a bug 155 | * :fire: `:fire:` when removing code or files 156 | * :green_heart: `:green_heart:` when fixing the CI build 157 | * :white_check_mark: `:white_check_mark:` when adding tests 158 | * :lock: `:lock:` when dealing with security 159 | * :arrow_up: `:arrow_up:` when upgrading dependencies 160 | * :arrow_down: `:arrow_down:` when downgrading dependencies 161 | * :shirt: `:shirt:` when removing linter warnings 162 | 163 | ### JavaScript Styleguide 164 | 165 | All JavaScript code is linted with [Prettier](https://prettier.io/). 166 | 167 | * Prefer the object spread operator (`{...anotherObj}`) to `Object.assign()` 168 | * Inline `export`s with expressions whenever possible 169 | ```js 170 | // Use this: 171 | export default class ClassName { 172 | 173 | } 174 | 175 | // Instead of: 176 | class ClassName { 177 | 178 | } 179 | export default ClassName 180 | ``` 181 | * Place requires in the following order: 182 | * Built in Node Modules (such as `path`) 183 | * Local Modules (using relative paths) 184 | * Place class properties in the following order: 185 | * Class methods and properties (methods starting with `static`) 186 | * Instance methods and properties 187 | 188 | ### CoffeeScript Styleguide 189 | 190 | * Set parameter defaults without spaces around the equal sign 191 | * `clear = (count=1) ->` instead of `clear = (count = 1) ->` 192 | * Use spaces around operators 193 | * `count + 1` instead of `count+1` 194 | * Use spaces after commas (unless separated by newlines) 195 | * Use parentheses if it improves code clarity. 196 | * Prefer alphabetic keywords to symbolic keywords: 197 | * `a is b` instead of `a == b` 198 | * Avoid spaces inside the curly-braces of hash literals: 199 | * `{a: 1, b: 2}` instead of `{ a: 1, b: 2 }` 200 | * Include a single line of whitespace between methods. 201 | * Capitalize initialisms and acronyms in names, except for the first word, which 202 | should be lower-case: 203 | * `getURI` instead of `getUri` 204 | * `uriToOpen` instead of `URIToOpen` 205 | * Use `slice()` to copy an array 206 | * Add an explicit `return` when your function ends with a `for`/`while` loop and 207 | you don't want it to return a collected array. 208 | * Use `this` instead of a standalone `@` 209 | * `return this` instead of `return @` 210 | * Place requires in the following order: 211 | * Built in Node Modules (such as `path`) 212 | * Local Modules (using relative paths) 213 | * Place class properties in the following order: 214 | * Class methods and properties (methods starting with a `@`) 215 | * Instance methods and properties 216 | 217 | ### Specs Styleguide 218 | 219 | - Include thoughtfully-worded, well-structured [Jasmine](https://jasmine.github.io/) specs in the `./spec` folder. 220 | - Treat `describe` as a noun or situation. 221 | - Treat `it` as a statement about state or how an operation changes state. 222 | 223 | #### Example 224 | 225 | ```coffee 226 | describe 'a dog', -> 227 | it 'barks', -> 228 | # spec here 229 | describe 'when the dog is happy', -> 230 | it 'wags its tail', -> 231 | # spec here 232 | ``` 233 | 234 | ### Documentation Styleguide 235 | 236 | * Use [Markdown](https://daringfireball.net/projects/markdown). 237 | * Reference methods and classes in markdown with the custom `{}` notation: 238 | * Reference classes with `{ClassName}` 239 | * Reference instance methods with `{ClassName::methodName}` 240 | * Reference class methods with `{ClassName.methodName}` 241 | 242 | #### Example 243 | 244 | ```coffee 245 | # Public: Disable the package with the given name. 246 | # 247 | # * `name` The {String} name of the package to disable. 248 | # * `options` (optional) The {Object} with disable options (default: {}): 249 | # * `trackTime` A {Boolean}, `true` to track the amount of time taken. 250 | # * `ignoreErrors` A {Boolean}, `true` to catch and ignore errors thrown. 251 | # * `callback` The {Function} to call after the package has been disabled. 252 | # 253 | # Returns `undefined`. 254 | disablePackage: (name, options, callback) -> 255 | ``` 256 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Elk Finance Smart Contracts 2 | 3 | This repository contains all of the smart contracts used to run [Elk Finance](https://elk.finance). 4 | 5 | Elk Finance uses three main contract templates: 6 | * ElkRouter: high-level interface for all Elk Exchange functionality 7 | * ElkFactory: creates and manages liquidity pairs 8 | * ElkPair: a liquidity pair made of two assets 9 | 10 | ## Deployed Contracts 11 | 12 | Please see https://docs.elk.finance/addresses for an up-to-date list of addresses of deployed contracts on supported chains. 13 | 14 | ## Compiling and Running 15 | 16 | ### Using Hardhat 17 | 18 | 1. Get [Hardhat](https://hardhat.org/). 19 | 2. Execute `yarn install` to prepare the environment. 20 | 3. Execute `yarn compile` to compile the contracts. 21 | 22 | ### Using Remix IDE 23 | 24 | A tutorial for using Remix is located [here](https://docs.avax.network/build/tutorials/platform/deploy-a-smart-contract-on-avalanche-using-remix-and-metamask). 25 | 26 | ## Development 27 | 28 | ### Accessing the ABI 29 | 30 | 1. Install into your project using `npm install --dev @elkdex/avax-exchange-contracts`. 31 | 2. Import the ABI: `import { abi as IPangolinPairABI } from '@elkdex/avax-exchange-contracts/artifacts/contracts/elk-core/interfaces/IElkPair.sol/IElkPair.json'`. 32 | 33 | ## Attribution 34 | 35 | These contracts were adapted from these Uniswap repos: [uniswap-v2-core](https://github.com/Uniswap/uniswap-v2-core), [uniswap-v2-periphery](https://github.com/Uniswap/uniswap-v2-core), and [uniswap-lib](https://github.com/Uniswap/uniswap-lib). 36 | -------------------------------------------------------------------------------- /contracts/elk-core/CalculateElkPairHash.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | import './ElkPair.sol'; 4 | 5 | contract CalculateElkPairHash { 6 | function getInitHash() public pure returns(bytes32){ 7 | bytes memory bytecode = type(ElkPair).creationCode; 8 | return keccak256(abi.encodePacked(bytecode)); 9 | } 10 | } -------------------------------------------------------------------------------- /contracts/elk-core/ElkERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | import './interfaces/IElkERC20.sol'; 4 | import './libraries/SafeMath.sol'; 5 | 6 | contract ElkERC20 is IElkERC20 { 7 | using SafeMath for uint; 8 | 9 | string public constant name = 'Elk Liquidity'; 10 | string public constant symbol = 'ELP'; 11 | uint8 public constant decimals = 18; 12 | uint public totalSupply; 13 | mapping(address => uint) public balanceOf; 14 | mapping(address => mapping(address => uint)) public allowance; 15 | 16 | bytes32 public DOMAIN_SEPARATOR; 17 | // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); 18 | bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; 19 | mapping(address => uint) public nonces; 20 | 21 | event Approval(address indexed owner, address indexed spender, uint value); 22 | event Transfer(address indexed from, address indexed to, uint value); 23 | 24 | constructor() public { 25 | uint chainId; 26 | assembly { 27 | chainId := chainid 28 | } 29 | DOMAIN_SEPARATOR = keccak256( 30 | abi.encode( 31 | keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), 32 | keccak256(bytes(name)), 33 | keccak256(bytes('1')), 34 | chainId, 35 | address(this) 36 | ) 37 | ); 38 | } 39 | 40 | function _mint(address to, uint value) internal { 41 | totalSupply = totalSupply.add(value); 42 | balanceOf[to] = balanceOf[to].add(value); 43 | emit Transfer(address(0), to, value); 44 | } 45 | 46 | function _burn(address from, uint value) internal { 47 | balanceOf[from] = balanceOf[from].sub(value); 48 | totalSupply = totalSupply.sub(value); 49 | emit Transfer(from, address(0), value); 50 | } 51 | 52 | function _approve(address owner, address spender, uint value) private { 53 | allowance[owner][spender] = value; 54 | emit Approval(owner, spender, value); 55 | } 56 | 57 | function _transfer(address from, address to, uint value) private { 58 | balanceOf[from] = balanceOf[from].sub(value); 59 | balanceOf[to] = balanceOf[to].add(value); 60 | emit Transfer(from, to, value); 61 | } 62 | 63 | function approve(address spender, uint value) external returns (bool) { 64 | _approve(msg.sender, spender, value); 65 | return true; 66 | } 67 | 68 | function transfer(address to, uint value) external returns (bool) { 69 | _transfer(msg.sender, to, value); 70 | return true; 71 | } 72 | 73 | function transferFrom(address from, address to, uint value) external returns (bool) { 74 | if (allowance[from][msg.sender] != uint(-1)) { 75 | allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); 76 | } 77 | _transfer(from, to, value); 78 | return true; 79 | } 80 | 81 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { 82 | require(deadline >= block.timestamp, 'Elk: EXPIRED'); 83 | bytes32 digest = keccak256( 84 | abi.encodePacked( 85 | '\x19\x01', 86 | DOMAIN_SEPARATOR, 87 | keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) 88 | ) 89 | ); 90 | address recoveredAddress = ecrecover(digest, v, r, s); 91 | require(recoveredAddress != address(0) && recoveredAddress == owner, 'Elk: INVALID_SIGNATURE'); 92 | _approve(owner, spender, value); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /contracts/elk-core/ElkFactory.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | import './interfaces/IElkFactory.sol'; 4 | import './ElkPair.sol'; 5 | 6 | contract ElkFactory is IElkFactory { 7 | address public feeTo; 8 | address public feeToSetter; 9 | 10 | mapping(address => mapping(address => address)) public getPair; 11 | address[] public allPairs; 12 | 13 | event PairCreated(address indexed token0, address indexed token1, address pair, uint); 14 | 15 | constructor(address _feeToSetter) public { 16 | feeToSetter = _feeToSetter; 17 | } 18 | 19 | function allPairsLength() external view returns (uint) { 20 | return allPairs.length; 21 | } 22 | 23 | function createPair(address tokenA, address tokenB) external returns (address pair) { 24 | require(tokenA != tokenB, 'Elk: IDENTICAL_ADDRESSES'); 25 | (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); 26 | require(token0 != address(0), 'Elk: ZERO_ADDRESS'); 27 | require(getPair[token0][token1] == address(0), 'Elk: PAIR_EXISTS'); // single check is sufficient 28 | bytes memory bytecode = type(ElkPair).creationCode; 29 | bytes32 salt = keccak256(abi.encodePacked(token0, token1)); 30 | assembly { 31 | pair := create2(0, add(bytecode, 32), mload(bytecode), salt) 32 | } 33 | IElkPair(pair).initialize(token0, token1); 34 | getPair[token0][token1] = pair; 35 | getPair[token1][token0] = pair; // populate mapping in the reverse direction 36 | allPairs.push(pair); 37 | emit PairCreated(token0, token1, pair, allPairs.length); 38 | } 39 | 40 | function setFeeTo(address _feeTo) external { 41 | require(msg.sender == feeToSetter, 'Elk: FORBIDDEN'); 42 | feeTo = _feeTo; 43 | } 44 | 45 | function setFeeToSetter(address _feeToSetter) external { 46 | require(msg.sender == feeToSetter, 'Elk: FORBIDDEN'); 47 | feeToSetter = _feeToSetter; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /contracts/elk-core/ElkPair.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | import './interfaces/IElkPair.sol'; 4 | import './ElkERC20.sol'; 5 | import './libraries/Math.sol'; 6 | import './libraries/UQ112x112.sol'; 7 | import './interfaces/IERC20.sol'; 8 | import './interfaces/IElkFactory.sol'; 9 | import './interfaces/IElkCallee.sol'; 10 | 11 | contract ElkPair is IElkPair, ElkERC20 { 12 | using SafeMath for uint; 13 | using UQ112x112 for uint224; 14 | 15 | uint public constant MINIMUM_LIQUIDITY = 10**3; 16 | bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); 17 | 18 | address public factory; 19 | address public token0; 20 | address public token1; 21 | 22 | uint112 private reserve0; // uses single storage slot, accessible via getReserves 23 | uint112 private reserve1; // uses single storage slot, accessible via getReserves 24 | uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves 25 | 26 | uint public price0CumulativeLast; 27 | uint public price1CumulativeLast; 28 | uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event 29 | 30 | uint private unlocked = 1; 31 | modifier lock() { 32 | require(unlocked == 1, 'Elk: LOCKED'); 33 | unlocked = 0; 34 | _; 35 | unlocked = 1; 36 | } 37 | 38 | function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { 39 | _reserve0 = reserve0; 40 | _reserve1 = reserve1; 41 | _blockTimestampLast = blockTimestampLast; 42 | } 43 | 44 | function _safeTransfer(address token, address to, uint value) private { 45 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); 46 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'Elk: TRANSFER_FAILED'); 47 | } 48 | 49 | event Mint(address indexed sender, uint amount0, uint amount1); 50 | event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); 51 | event Swap( 52 | address indexed sender, 53 | uint amount0In, 54 | uint amount1In, 55 | uint amount0Out, 56 | uint amount1Out, 57 | address indexed to 58 | ); 59 | event Sync(uint112 reserve0, uint112 reserve1); 60 | 61 | constructor() public { 62 | factory = msg.sender; 63 | } 64 | 65 | // called once by the factory at time of deployment 66 | function initialize(address _token0, address _token1) external { 67 | require(msg.sender == factory, 'Elk: FORBIDDEN'); // sufficient check 68 | token0 = _token0; 69 | token1 = _token1; 70 | } 71 | 72 | // update reserves and, on the first call per block, price accumulators 73 | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { 74 | require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Elk: OVERFLOW'); 75 | uint32 blockTimestamp = uint32(block.timestamp % 2**32); 76 | uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired 77 | if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { 78 | // * never overflows, and + overflow is desired 79 | price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; 80 | price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; 81 | } 82 | reserve0 = uint112(balance0); 83 | reserve1 = uint112(balance1); 84 | blockTimestampLast = blockTimestamp; 85 | emit Sync(reserve0, reserve1); 86 | } 87 | 88 | // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) 89 | function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { 90 | address feeTo = IElkFactory(factory).feeTo(); 91 | feeOn = feeTo != address(0); 92 | uint _kLast = kLast; // gas savings 93 | if (feeOn) { 94 | if (_kLast != 0) { 95 | uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); 96 | uint rootKLast = Math.sqrt(_kLast); 97 | if (rootK > rootKLast) { 98 | uint numerator = totalSupply.mul(rootK.sub(rootKLast)); 99 | uint denominator = rootK.mul(5).add(rootKLast); 100 | uint liquidity = numerator / denominator; 101 | if (liquidity > 0) _mint(feeTo, liquidity); 102 | } 103 | } 104 | } else if (_kLast != 0) { 105 | kLast = 0; 106 | } 107 | } 108 | 109 | // this low-level function should be called from a contract which performs important safety checks 110 | function mint(address to) external lock returns (uint liquidity) { 111 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 112 | uint balance0 = IERC20(token0).balanceOf(address(this)); 113 | uint balance1 = IERC20(token1).balanceOf(address(this)); 114 | uint amount0 = balance0.sub(_reserve0); 115 | uint amount1 = balance1.sub(_reserve1); 116 | 117 | bool feeOn = _mintFee(_reserve0, _reserve1); 118 | uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee 119 | if (_totalSupply == 0) { 120 | liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); 121 | _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens 122 | } else { 123 | liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); 124 | } 125 | require(liquidity > 0, 'Elk: INSUFFICIENT_LIQUIDITY_MINTED'); 126 | _mint(to, liquidity); 127 | 128 | _update(balance0, balance1, _reserve0, _reserve1); 129 | if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 130 | emit Mint(msg.sender, amount0, amount1); 131 | } 132 | 133 | // this low-level function should be called from a contract which performs important safety checks 134 | function burn(address to) external lock returns (uint amount0, uint amount1) { 135 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 136 | address _token0 = token0; // gas savings 137 | address _token1 = token1; // gas savings 138 | uint balance0 = IERC20(_token0).balanceOf(address(this)); 139 | uint balance1 = IERC20(_token1).balanceOf(address(this)); 140 | uint liquidity = balanceOf[address(this)]; 141 | 142 | bool feeOn = _mintFee(_reserve0, _reserve1); 143 | uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee 144 | amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution 145 | amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution 146 | require(amount0 > 0 && amount1 > 0, 'Elk: INSUFFICIENT_LIQUIDITY_BURNED'); 147 | _burn(address(this), liquidity); 148 | _safeTransfer(_token0, to, amount0); 149 | _safeTransfer(_token1, to, amount1); 150 | balance0 = IERC20(_token0).balanceOf(address(this)); 151 | balance1 = IERC20(_token1).balanceOf(address(this)); 152 | 153 | _update(balance0, balance1, _reserve0, _reserve1); 154 | if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 155 | emit Burn(msg.sender, amount0, amount1, to); 156 | } 157 | 158 | // this low-level function should be called from a contract which performs important safety checks 159 | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { 160 | require(amount0Out > 0 || amount1Out > 0, 'Elk: INSUFFICIENT_OUTPUT_AMOUNT'); 161 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 162 | require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Elk: INSUFFICIENT_LIQUIDITY'); 163 | 164 | uint balance0; 165 | uint balance1; 166 | { // scope for _token{0,1}, avoids stack too deep errors 167 | address _token0 = token0; 168 | address _token1 = token1; 169 | require(to != _token0 && to != _token1, 'Elk: INVALID_TO'); 170 | if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens 171 | if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens 172 | if (data.length > 0) IElkCallee(to).elkCall(msg.sender, amount0Out, amount1Out, data); 173 | balance0 = IERC20(_token0).balanceOf(address(this)); 174 | balance1 = IERC20(_token1).balanceOf(address(this)); 175 | } 176 | uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; 177 | uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; 178 | require(amount0In > 0 || amount1In > 0, 'Elk: INSUFFICIENT_INPUT_AMOUNT'); 179 | { // scope for reserve{0,1}Adjusted, avoids stack too deep errors 180 | uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); 181 | uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); 182 | require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'Elk: K'); 183 | } 184 | 185 | _update(balance0, balance1, _reserve0, _reserve1); 186 | emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); 187 | } 188 | 189 | // force balances to match reserves 190 | function skim(address to) external lock { 191 | address _token0 = token0; // gas savings 192 | address _token1 = token1; // gas savings 193 | _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); 194 | _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); 195 | } 196 | 197 | // force reserves to match balances 198 | function sync() external lock { 199 | _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /contracts/elk-core/interfaces/IERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IERC20 { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external view returns (string memory); 8 | function symbol() external view returns (string memory); 9 | function decimals() external view returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | } 18 | -------------------------------------------------------------------------------- /contracts/elk-core/interfaces/IElkCallee.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IElkCallee { 4 | function elkCall(address sender, uint amount0, uint amount1, bytes calldata data) external; 5 | } 6 | -------------------------------------------------------------------------------- /contracts/elk-core/interfaces/IElkERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IElkERC20 { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external pure returns (string memory); 8 | function symbol() external pure returns (string memory); 9 | function decimals() external pure returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | 18 | function DOMAIN_SEPARATOR() external view returns (bytes32); 19 | function PERMIT_TYPEHASH() external pure returns (bytes32); 20 | function nonces(address owner) external view returns (uint); 21 | 22 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 23 | } 24 | -------------------------------------------------------------------------------- /contracts/elk-core/interfaces/IElkFactory.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IElkFactory { 4 | event PairCreated(address indexed token0, address indexed token1, address pair, uint); 5 | 6 | function feeTo() external view returns (address); 7 | function feeToSetter() external view returns (address); 8 | 9 | function getPair(address tokenA, address tokenB) external view returns (address pair); 10 | function allPairs(uint) external view returns (address pair); 11 | function allPairsLength() external view returns (uint); 12 | 13 | function createPair(address tokenA, address tokenB) external returns (address pair); 14 | 15 | function setFeeTo(address) external; 16 | function setFeeToSetter(address) external; 17 | } 18 | -------------------------------------------------------------------------------- /contracts/elk-core/interfaces/IElkPair.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IElkPair { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external pure returns (string memory); 8 | function symbol() external pure returns (string memory); 9 | function decimals() external pure returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | 18 | function DOMAIN_SEPARATOR() external view returns (bytes32); 19 | function PERMIT_TYPEHASH() external pure returns (bytes32); 20 | function nonces(address owner) external view returns (uint); 21 | 22 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 23 | 24 | event Mint(address indexed sender, uint amount0, uint amount1); 25 | event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); 26 | event Swap( 27 | address indexed sender, 28 | uint amount0In, 29 | uint amount1In, 30 | uint amount0Out, 31 | uint amount1Out, 32 | address indexed to 33 | ); 34 | event Sync(uint112 reserve0, uint112 reserve1); 35 | 36 | function MINIMUM_LIQUIDITY() external pure returns (uint); 37 | function factory() external view returns (address); 38 | function token0() external view returns (address); 39 | function token1() external view returns (address); 40 | function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); 41 | function price0CumulativeLast() external view returns (uint); 42 | function price1CumulativeLast() external view returns (uint); 43 | function kLast() external view returns (uint); 44 | 45 | function mint(address to) external returns (uint liquidity); 46 | function burn(address to) external returns (uint amount0, uint amount1); 47 | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; 48 | function skim(address to) external; 49 | function sync() external; 50 | 51 | function initialize(address, address) external; 52 | } 53 | -------------------------------------------------------------------------------- /contracts/elk-core/libraries/Math.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | // a library for performing various math operations 4 | 5 | library Math { 6 | function min(uint x, uint y) internal pure returns (uint z) { 7 | z = x < y ? x : y; 8 | } 9 | 10 | // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) 11 | function sqrt(uint y) internal pure returns (uint z) { 12 | if (y > 3) { 13 | z = y; 14 | uint x = y / 2 + 1; 15 | while (x < z) { 16 | z = x; 17 | x = (y / x + x) / 2; 18 | } 19 | } else if (y != 0) { 20 | z = 1; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /contracts/elk-core/libraries/SafeMath.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) 4 | 5 | library SafeMath { 6 | function add(uint x, uint y) internal pure returns (uint z) { 7 | require((z = x + y) >= x, 'ds-math-add-overflow'); 8 | } 9 | 10 | function sub(uint x, uint y) internal pure returns (uint z) { 11 | require((z = x - y) <= x, 'ds-math-sub-underflow'); 12 | } 13 | 14 | function mul(uint x, uint y) internal pure returns (uint z) { 15 | require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /contracts/elk-core/libraries/UQ112x112.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.5.16; 2 | 3 | // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) 4 | 5 | // range: [0, 2**112 - 1] 6 | // resolution: 1 / 2**112 7 | 8 | library UQ112x112 { 9 | uint224 constant Q112 = 2**112; 10 | 11 | // encode a uint112 as a UQ112x112 12 | function encode(uint112 y) internal pure returns (uint224 z) { 13 | z = uint224(y) * Q112; // never overflows 14 | } 15 | 16 | // divide a UQ112x112 by a uint112, returning a UQ112x112 17 | function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { 18 | z = x / uint224(y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/AddressStringUtil.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | pragma solidity >=0.5.0 <0.8.0; 4 | 5 | library AddressStringUtil { 6 | // converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2) 7 | function toAsciiString(address addr, uint256 len) internal pure returns (string memory) { 8 | require(len % 2 == 0 && len > 0 && len <= 40, 'AddressStringUtil: INVALID_LEN'); 9 | 10 | bytes memory s = new bytes(len); 11 | uint256 addrNum = uint256(addr); 12 | for (uint256 i = 0; i < len / 2; i++) { 13 | // shift right and truncate all but the least significant byte to extract the byte at position 19-i 14 | uint8 b = uint8(addrNum >> (8 * (19 - i))); 15 | // first hex character is the most significant 4 bits 16 | uint8 hi = b >> 4; 17 | // second hex character is the least significant 4 bits 18 | uint8 lo = b - (hi << 4); 19 | s[2 * i] = char(hi); 20 | s[2 * i + 1] = char(lo); 21 | } 22 | return string(s); 23 | } 24 | 25 | // hi and lo are only 4 bits and between 0 and 16 26 | // this method converts those values to the unicode/ascii code point for the hex representation 27 | // uses upper case for the characters 28 | function char(uint8 b) private pure returns (bytes1 c) { 29 | if (b < 10) { 30 | return bytes1(b + 0x30); 31 | } else { 32 | return bytes1(b + 0x37); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/Babylonian.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | pragma solidity >=0.4.0; 4 | 5 | // computes square roots using the babylonian method 6 | // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method 7 | library Babylonian { 8 | function sqrt(uint256 y) internal pure returns (uint256 z) { 9 | if (y > 3) { 10 | z = y; 11 | uint256 x = y / 2 + 1; 12 | while (x < z) { 13 | z = x; 14 | x = (y / x + x) / 2; 15 | } 16 | } else if (y != 0) { 17 | z = 1; 18 | } 19 | // else z = 0 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/FixedPoint.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity >=0.4.0 <0.8.0; 3 | 4 | import './FullMath.sol'; 5 | import './Babylonian.sol'; 6 | 7 | // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) 8 | library FixedPoint { 9 | // range: [0, 2**112 - 1] 10 | // resolution: 1 / 2**112 11 | struct uq112x112 { 12 | uint224 _x; 13 | } 14 | 15 | // range: [0, 2**144 - 1] 16 | // resolution: 1 / 2**112 17 | struct uq144x112 { 18 | uint256 _x; 19 | } 20 | 21 | uint8 private constant RESOLUTION = 112; 22 | uint256 private constant Q112 = 0x10000000000000000000000000000; 23 | uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; 24 | uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) 25 | 26 | // encode a uint112 as a UQ112x112 27 | function encode(uint112 x) internal pure returns (uq112x112 memory) { 28 | return uq112x112(uint224(x) << RESOLUTION); 29 | } 30 | 31 | // encodes a uint144 as a UQ144x112 32 | function encode144(uint144 x) internal pure returns (uq144x112 memory) { 33 | return uq144x112(uint256(x) << RESOLUTION); 34 | } 35 | 36 | // decode a UQ112x112 into a uint112 by truncating after the radix point 37 | function decode(uq112x112 memory self) internal pure returns (uint112) { 38 | return uint112(self._x >> RESOLUTION); 39 | } 40 | 41 | // decode a UQ144x112 into a uint144 by truncating after the radix point 42 | function decode144(uq144x112 memory self) internal pure returns (uint144) { 43 | return uint144(self._x >> RESOLUTION); 44 | } 45 | 46 | // multiply a UQ112x112 by a uint, returning a UQ144x112 47 | // reverts on overflow 48 | function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { 49 | uint256 z = 0; 50 | require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint: MUL_OVERFLOW'); 51 | return uq144x112(z); 52 | } 53 | 54 | // multiply a UQ112x112 by an int and decode, returning an int 55 | // reverts on overflow 56 | function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { 57 | uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); 58 | require(z < 2**255, 'FixedPoint: MULI_OVERFLOW'); 59 | return y < 0 ? -int256(z) : int256(z); 60 | } 61 | 62 | // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 63 | // lossy 64 | function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { 65 | if (self._x == 0 || other._x == 0) { 66 | return uq112x112(0); 67 | } 68 | uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 69 | uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 70 | uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 71 | uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 72 | 73 | // partial products 74 | uint224 upper = uint224(upper_self) * upper_other; // * 2^0 75 | uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 76 | uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 77 | uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 78 | 79 | // so the bit shift does not overflow 80 | require(upper <= uint112(-1), 'FixedPoint: MULUQ_OVERFLOW_UPPER'); 81 | 82 | // this cannot exceed 256 bits, all values are 224 bits 83 | uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); 84 | 85 | // so the cast does not overflow 86 | require(sum <= uint224(-1), 'FixedPoint: MULUQ_OVERFLOW_SUM'); 87 | 88 | return uq112x112(uint224(sum)); 89 | } 90 | 91 | // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 92 | function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { 93 | require(other._x > 0, 'FixedPoint: DIV_BY_ZERO_DIVUQ'); 94 | if (self._x == other._x) { 95 | return uq112x112(uint224(Q112)); 96 | } 97 | if (self._x <= uint144(-1)) { 98 | uint256 value = (uint256(self._x) << RESOLUTION) / other._x; 99 | require(value <= uint224(-1), 'FixedPoint: DIVUQ_OVERFLOW'); 100 | return uq112x112(uint224(value)); 101 | } 102 | 103 | uint256 result = FullMath.mulDiv(Q112, self._x, other._x); 104 | require(result <= uint224(-1), 'FixedPoint: DIVUQ_OVERFLOW'); 105 | return uq112x112(uint224(result)); 106 | } 107 | 108 | // returns a UQ112x112 which represents the ratio of the numerator to the denominator 109 | // lossy 110 | function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { 111 | require(denominator > 0, 'FixedPoint: DIV_BY_ZERO_FRACTION'); 112 | return uq112x112((uint224(numerator) << RESOLUTION) / denominator); 113 | } 114 | 115 | // take the reciprocal of a UQ112x112 116 | // reverts on overflow 117 | // lossy 118 | function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { 119 | require(self._x > 1, 'FixedPoint: DIV_BY_ZERO_RECIPROCAL_OR_OVERFLOW'); 120 | return uq112x112(uint224(Q224 / self._x)); 121 | } 122 | 123 | // square root of a UQ112x112 124 | // lossy between 0/1 and 40 bits 125 | function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { 126 | if (self._x <= uint144(-1)) { 127 | return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); 128 | } 129 | 130 | uint8 safeShiftBits = 32; 131 | while (safeShiftBits < 112) { 132 | if (self._x < (uint256(1) << (256 - safeShiftBits - 2))) { 133 | safeShiftBits += 2; 134 | } else { 135 | break; 136 | } 137 | } 138 | return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/FullMath.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: CC-BY-4.0 2 | pragma solidity >=0.4.0 <0.8.0; 3 | 4 | // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 5 | // license is CC-BY-4.0 6 | library FullMath { 7 | function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { 8 | uint256 mm = mulmod(x, y, uint256(-1)); 9 | l = x * y; 10 | h = mm - l; 11 | if (mm < l) h -= 1; 12 | } 13 | 14 | function fullDiv( 15 | uint256 l, 16 | uint256 h, 17 | uint256 d 18 | ) private pure returns (uint256) { 19 | uint256 pow2 = d & -d; 20 | d /= pow2; 21 | l /= pow2; 22 | l += h * ((-pow2) / pow2 + 1); 23 | uint256 r = 1; 24 | r *= 2 - d * r; 25 | r *= 2 - d * r; 26 | r *= 2 - d * r; 27 | r *= 2 - d * r; 28 | r *= 2 - d * r; 29 | r *= 2 - d * r; 30 | r *= 2 - d * r; 31 | r *= 2 - d * r; 32 | return l * r; 33 | } 34 | 35 | function mulDiv( 36 | uint256 x, 37 | uint256 y, 38 | uint256 d 39 | ) internal pure returns (uint256) { 40 | (uint256 l, uint256 h) = fullMul(x, y); 41 | uint256 mm = mulmod(x, y, d); 42 | if (mm > l) h -= 1; 43 | l -= mm; 44 | require(h < d, 'FullMath: FULLDIV_OVERFLOW'); 45 | return fullDiv(l, h, d); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/PairNamer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | pragma solidity >=0.5.0; 4 | 5 | import './SafeERC20Namer.sol'; 6 | 7 | // produces names for pairs of tokens using Elk's naming scheme 8 | library PairNamer { 9 | string private constant TOKEN_SYMBOL_PREFIX = 'ELK:'; 10 | string private constant TOKEN_SEPARATOR = ':'; 11 | 12 | // produces a pair descriptor in the format of `${prefix}${name0}:${name1}${suffix}` 13 | function pairName( 14 | address token0, 15 | address token1, 16 | string memory prefix, 17 | string memory suffix 18 | ) internal view returns (string memory) { 19 | return 20 | string( 21 | abi.encodePacked( 22 | prefix, 23 | SafeERC20Namer.tokenName(token0), 24 | TOKEN_SEPARATOR, 25 | SafeERC20Namer.tokenName(token1), 26 | suffix 27 | ) 28 | ); 29 | } 30 | 31 | // produces a pair symbol in the format of `ELK:${symbol0}:${symbol1}${suffix}` 32 | function pairSymbol( 33 | address token0, 34 | address token1, 35 | string memory suffix 36 | ) internal view returns (string memory) { 37 | return 38 | string( 39 | abi.encodePacked( 40 | TOKEN_SYMBOL_PREFIX, 41 | SafeERC20Namer.tokenSymbol(token0), 42 | TOKEN_SEPARATOR, 43 | SafeERC20Namer.tokenSymbol(token1), 44 | suffix 45 | ) 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/SafeERC20Namer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | pragma solidity >=0.5.0; 4 | 5 | import './AddressStringUtil.sol'; 6 | 7 | // produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32 8 | // this library will always produce a string symbol to represent the token 9 | library SafeERC20Namer { 10 | function bytes32ToString(bytes32 x) private pure returns (string memory) { 11 | bytes memory bytesString = new bytes(32); 12 | uint256 charCount = 0; 13 | for (uint256 j = 0; j < 32; j++) { 14 | bytes1 char = x[j]; 15 | if (char != 0) { 16 | bytesString[charCount] = char; 17 | charCount++; 18 | } 19 | } 20 | bytes memory bytesStringTrimmed = new bytes(charCount); 21 | for (uint256 j = 0; j < charCount; j++) { 22 | bytesStringTrimmed[j] = bytesString[j]; 23 | } 24 | return string(bytesStringTrimmed); 25 | } 26 | 27 | // assumes the data is in position 2 28 | function parseStringData(bytes memory b) private pure returns (string memory) { 29 | uint256 charCount = 0; 30 | // first parse the charCount out of the data 31 | for (uint256 i = 32; i < 64; i++) { 32 | charCount <<= 8; 33 | charCount += uint8(b[i]); 34 | } 35 | 36 | bytes memory bytesStringTrimmed = new bytes(charCount); 37 | for (uint256 i = 0; i < charCount; i++) { 38 | bytesStringTrimmed[i] = b[i + 64]; 39 | } 40 | 41 | return string(bytesStringTrimmed); 42 | } 43 | 44 | // uses a heuristic to produce a token name from the address 45 | // the heuristic returns the full hex of the address string in upper case 46 | function addressToName(address token) private pure returns (string memory) { 47 | return AddressStringUtil.toAsciiString(token, 40); 48 | } 49 | 50 | // uses a heuristic to produce a token symbol from the address 51 | // the heuristic returns the first 6 hex of the address string in upper case 52 | function addressToSymbol(address token) private pure returns (string memory) { 53 | return AddressStringUtil.toAsciiString(token, 6); 54 | } 55 | 56 | // calls an external view token contract method that returns a symbol or name, and parses the output into a string 57 | function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) { 58 | (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector)); 59 | // if not implemented, or returns empty data, return empty string 60 | if (!success || data.length == 0) { 61 | return ''; 62 | } 63 | // bytes32 data always has length 32 64 | if (data.length == 32) { 65 | bytes32 decoded = abi.decode(data, (bytes32)); 66 | return bytes32ToString(decoded); 67 | } else if (data.length > 64) { 68 | return abi.decode(data, (string)); 69 | } 70 | return ''; 71 | } 72 | 73 | // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address 74 | function tokenSymbol(address token) internal view returns (string memory) { 75 | // 0x95d89b41 = bytes4(keccak256("symbol()")) 76 | string memory symbol = callAndParseStringReturn(token, 0x95d89b41); 77 | if (bytes(symbol).length == 0) { 78 | // fallback to 6 uppercase hex of address 79 | return addressToSymbol(token); 80 | } 81 | return symbol; 82 | } 83 | 84 | // attempts to extract the token name. if it does not implement name, returns a name derived from the address 85 | function tokenName(address token) internal view returns (string memory) { 86 | // 0x06fdde03 = bytes4(keccak256("name()")) 87 | string memory name = callAndParseStringReturn(token, 0x06fdde03); 88 | if (bytes(name).length == 0) { 89 | // fallback to full hex of address 90 | return addressToName(token); 91 | } 92 | return name; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /contracts/elk-lib/libraries/TransferHelper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | pragma solidity >=0.6.0; 4 | 5 | // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false 6 | library TransferHelper { 7 | function safeApprove( 8 | address token, 9 | address to, 10 | uint256 value 11 | ) internal { 12 | // bytes4(keccak256(bytes('approve(address,uint256)'))); 13 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); 14 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); 15 | } 16 | 17 | function safeTransfer( 18 | address token, 19 | address to, 20 | uint256 value 21 | ) internal { 22 | // bytes4(keccak256(bytes('transfer(address,uint256)'))); 23 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); 24 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); 25 | } 26 | 27 | function safeTransferFrom( 28 | address token, 29 | address from, 30 | address to, 31 | uint256 value 32 | ) internal { 33 | // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); 34 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); 35 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); 36 | } 37 | 38 | function safeTransferETH(address to, uint256 value) internal { 39 | (bool success, ) = to.call{value: value}(new bytes(0)); 40 | require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /contracts/elk-periphery/ElkRouter.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.6.6; 2 | 3 | import '../elk-core/interfaces/IElkFactory.sol'; 4 | import '../elk-lib/libraries/TransferHelper.sol'; 5 | 6 | import './interfaces/IElkRouter.sol'; 7 | import './libraries/ElkLibrary.sol'; 8 | import './libraries/SafeMath.sol'; 9 | import './interfaces/IERC20.sol'; 10 | import './interfaces/IWETH.sol'; 11 | 12 | contract ElkRouter is IElkRouter { 13 | using SafeMath for uint; 14 | 15 | address public immutable override factory; 16 | address public immutable override WETH; 17 | 18 | modifier ensure(uint deadline) { 19 | require(deadline >= block.timestamp, 'ElkRouter: EXPIRED'); 20 | _; 21 | } 22 | 23 | constructor(address _factory, address _WETH) public { 24 | factory = _factory; 25 | WETH = _WETH; 26 | } 27 | 28 | receive() external payable { 29 | assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract 30 | } 31 | 32 | // **** ADD LIQUIDITY **** 33 | function _addLiquidity( 34 | address tokenA, 35 | address tokenB, 36 | uint amountADesired, 37 | uint amountBDesired, 38 | uint amountAMin, 39 | uint amountBMin 40 | ) internal virtual returns (uint amountA, uint amountB) { 41 | // create the pair if it doesn't exist yet 42 | if (IElkFactory(factory).getPair(tokenA, tokenB) == address(0)) { 43 | IElkFactory(factory).createPair(tokenA, tokenB); 44 | } 45 | (uint reserveA, uint reserveB) = ElkLibrary.getReserves(factory, tokenA, tokenB); 46 | if (reserveA == 0 && reserveB == 0) { 47 | (amountA, amountB) = (amountADesired, amountBDesired); 48 | } else { 49 | uint amountBOptimal = ElkLibrary.quote(amountADesired, reserveA, reserveB); 50 | if (amountBOptimal <= amountBDesired) { 51 | require(amountBOptimal >= amountBMin, 'ElkRouter: INSUFFICIENT_B_AMOUNT'); 52 | (amountA, amountB) = (amountADesired, amountBOptimal); 53 | } else { 54 | uint amountAOptimal = ElkLibrary.quote(amountBDesired, reserveB, reserveA); 55 | assert(amountAOptimal <= amountADesired); 56 | require(amountAOptimal >= amountAMin, 'ElkRouter: INSUFFICIENT_A_AMOUNT'); 57 | (amountA, amountB) = (amountAOptimal, amountBDesired); 58 | } 59 | } 60 | } 61 | function addLiquidity( 62 | address tokenA, 63 | address tokenB, 64 | uint amountADesired, 65 | uint amountBDesired, 66 | uint amountAMin, 67 | uint amountBMin, 68 | address to, 69 | uint deadline 70 | ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { 71 | (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); 72 | address pair = ElkLibrary.pairFor(factory, tokenA, tokenB); 73 | TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); 74 | TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); 75 | liquidity = IElkPair(pair).mint(to); 76 | } 77 | function addLiquidityETH( 78 | address token, 79 | uint amountTokenDesired, 80 | uint amountTokenMin, 81 | uint amountETHMin, 82 | address to, 83 | uint deadline 84 | ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { 85 | (amountToken, amountETH) = _addLiquidity( 86 | token, 87 | WETH, 88 | amountTokenDesired, 89 | msg.value, 90 | amountTokenMin, 91 | amountETHMin 92 | ); 93 | address pair = ElkLibrary.pairFor(factory, token, WETH); 94 | TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); 95 | IWETH(WETH).deposit{value: amountETH}(); 96 | assert(IWETH(WETH).transfer(pair, amountETH)); 97 | liquidity = IElkPair(pair).mint(to); 98 | // refund dust ETH, if any 99 | if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); 100 | } 101 | 102 | // **** REMOVE LIQUIDITY **** 103 | function removeLiquidity( 104 | address tokenA, 105 | address tokenB, 106 | uint liquidity, 107 | uint amountAMin, 108 | uint amountBMin, 109 | address to, 110 | uint deadline 111 | ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { 112 | address pair = ElkLibrary.pairFor(factory, tokenA, tokenB); 113 | IElkPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair 114 | (uint amount0, uint amount1) = IElkPair(pair).burn(to); 115 | (address token0,) = ElkLibrary.sortTokens(tokenA, tokenB); 116 | (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); 117 | require(amountA >= amountAMin, 'ElkRouter: INSUFFICIENT_A_AMOUNT'); 118 | require(amountB >= amountBMin, 'ElkRouter: INSUFFICIENT_B_AMOUNT'); 119 | } 120 | function removeLiquidityETH( 121 | address token, 122 | uint liquidity, 123 | uint amountTokenMin, 124 | uint amountETHMin, 125 | address to, 126 | uint deadline 127 | ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { 128 | (amountToken, amountETH) = removeLiquidity( 129 | token, 130 | WETH, 131 | liquidity, 132 | amountTokenMin, 133 | amountETHMin, 134 | address(this), 135 | deadline 136 | ); 137 | TransferHelper.safeTransfer(token, to, amountToken); 138 | IWETH(WETH).withdraw(amountETH); 139 | TransferHelper.safeTransferETH(to, amountETH); 140 | } 141 | function removeLiquidityWithPermit( 142 | address tokenA, 143 | address tokenB, 144 | uint liquidity, 145 | uint amountAMin, 146 | uint amountBMin, 147 | address to, 148 | uint deadline, 149 | bool approveMax, uint8 v, bytes32 r, bytes32 s 150 | ) external virtual override returns (uint amountA, uint amountB) { 151 | address pair = ElkLibrary.pairFor(factory, tokenA, tokenB); 152 | uint value = approveMax ? uint(-1) : liquidity; 153 | IElkPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); 154 | (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); 155 | } 156 | function removeLiquidityETHWithPermit( 157 | address token, 158 | uint liquidity, 159 | uint amountTokenMin, 160 | uint amountETHMin, 161 | address to, 162 | uint deadline, 163 | bool approveMax, uint8 v, bytes32 r, bytes32 s 164 | ) external virtual override returns (uint amountToken, uint amountETH) { 165 | address pair = ElkLibrary.pairFor(factory, token, WETH); 166 | uint value = approveMax ? uint(-1) : liquidity; 167 | IElkPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); 168 | (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); 169 | } 170 | 171 | // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** 172 | function removeLiquidityETHSupportingFeeOnTransferTokens( 173 | address token, 174 | uint liquidity, 175 | uint amountTokenMin, 176 | uint amountETHMin, 177 | address to, 178 | uint deadline 179 | ) public virtual override ensure(deadline) returns (uint amountETH) { 180 | (, amountETH) = removeLiquidity( 181 | token, 182 | WETH, 183 | liquidity, 184 | amountTokenMin, 185 | amountETHMin, 186 | address(this), 187 | deadline 188 | ); 189 | TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); 190 | IWETH(WETH).withdraw(amountETH); 191 | TransferHelper.safeTransferETH(to, amountETH); 192 | } 193 | function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( 194 | address token, 195 | uint liquidity, 196 | uint amountTokenMin, 197 | uint amountETHMin, 198 | address to, 199 | uint deadline, 200 | bool approveMax, uint8 v, bytes32 r, bytes32 s 201 | ) external virtual override returns (uint amountETH) { 202 | address pair = ElkLibrary.pairFor(factory, token, WETH); 203 | uint value = approveMax ? uint(-1) : liquidity; 204 | IElkPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); 205 | amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( 206 | token, liquidity, amountTokenMin, amountETHMin, to, deadline 207 | ); 208 | } 209 | 210 | // **** SWAP **** 211 | // requires the initial amount to have already been sent to the first pair 212 | function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { 213 | for (uint i; i < path.length - 1; i++) { 214 | (address input, address output) = (path[i], path[i + 1]); 215 | (address token0,) = ElkLibrary.sortTokens(input, output); 216 | uint amountOut = amounts[i + 1]; 217 | (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); 218 | address to = i < path.length - 2 ? ElkLibrary.pairFor(factory, output, path[i + 2]) : _to; 219 | IElkPair(ElkLibrary.pairFor(factory, input, output)).swap( 220 | amount0Out, amount1Out, to, new bytes(0) 221 | ); 222 | } 223 | } 224 | function swapExactTokensForTokens( 225 | uint amountIn, 226 | uint amountOutMin, 227 | address[] calldata path, 228 | address to, 229 | uint deadline 230 | ) external virtual override ensure(deadline) returns (uint[] memory amounts) { 231 | amounts = ElkLibrary.getAmountsOut(factory, amountIn, path); 232 | require(amounts[amounts.length - 1] >= amountOutMin, 'ElkRouter: INSUFFICIENT_OUTPUT_AMOUNT'); 233 | TransferHelper.safeTransferFrom( 234 | path[0], msg.sender, ElkLibrary.pairFor(factory, path[0], path[1]), amounts[0] 235 | ); 236 | _swap(amounts, path, to); 237 | } 238 | function swapTokensForExactTokens( 239 | uint amountOut, 240 | uint amountInMax, 241 | address[] calldata path, 242 | address to, 243 | uint deadline 244 | ) external virtual override ensure(deadline) returns (uint[] memory amounts) { 245 | amounts = ElkLibrary.getAmountsIn(factory, amountOut, path); 246 | require(amounts[0] <= amountInMax, 'ElkRouter: EXCESSIVE_INPUT_AMOUNT'); 247 | TransferHelper.safeTransferFrom( 248 | path[0], msg.sender, ElkLibrary.pairFor(factory, path[0], path[1]), amounts[0] 249 | ); 250 | _swap(amounts, path, to); 251 | } 252 | function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) 253 | external 254 | virtual 255 | override 256 | payable 257 | ensure(deadline) 258 | returns (uint[] memory amounts) 259 | { 260 | require(path[0] == WETH, 'ElkRouter: INVALID_PATH'); 261 | amounts = ElkLibrary.getAmountsOut(factory, msg.value, path); 262 | require(amounts[amounts.length - 1] >= amountOutMin, 'ElkRouter: INSUFFICIENT_OUTPUT_AMOUNT'); 263 | IWETH(WETH).deposit{value: amounts[0]}(); 264 | assert(IWETH(WETH).transfer(ElkLibrary.pairFor(factory, path[0], path[1]), amounts[0])); 265 | _swap(amounts, path, to); 266 | } 267 | function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) 268 | external 269 | virtual 270 | override 271 | ensure(deadline) 272 | returns (uint[] memory amounts) 273 | { 274 | require(path[path.length - 1] == WETH, 'ElkRouter: INVALID_PATH'); 275 | amounts = ElkLibrary.getAmountsIn(factory, amountOut, path); 276 | require(amounts[0] <= amountInMax, 'ElkRouter: EXCESSIVE_INPUT_AMOUNT'); 277 | TransferHelper.safeTransferFrom( 278 | path[0], msg.sender, ElkLibrary.pairFor(factory, path[0], path[1]), amounts[0] 279 | ); 280 | _swap(amounts, path, address(this)); 281 | IWETH(WETH).withdraw(amounts[amounts.length - 1]); 282 | TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); 283 | } 284 | function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) 285 | external 286 | virtual 287 | override 288 | ensure(deadline) 289 | returns (uint[] memory amounts) 290 | { 291 | require(path[path.length - 1] == WETH, 'ElkRouter: INVALID_PATH'); 292 | amounts = ElkLibrary.getAmountsOut(factory, amountIn, path); 293 | require(amounts[amounts.length - 1] >= amountOutMin, 'ElkRouter: INSUFFICIENT_OUTPUT_AMOUNT'); 294 | TransferHelper.safeTransferFrom( 295 | path[0], msg.sender, ElkLibrary.pairFor(factory, path[0], path[1]), amounts[0] 296 | ); 297 | _swap(amounts, path, address(this)); 298 | IWETH(WETH).withdraw(amounts[amounts.length - 1]); 299 | TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); 300 | } 301 | function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) 302 | external 303 | virtual 304 | override 305 | payable 306 | ensure(deadline) 307 | returns (uint[] memory amounts) 308 | { 309 | require(path[0] == WETH, 'ElkRouter: INVALID_PATH'); 310 | amounts = ElkLibrary.getAmountsIn(factory, amountOut, path); 311 | require(amounts[0] <= msg.value, 'ElkRouter: EXCESSIVE_INPUT_AMOUNT'); 312 | IWETH(WETH).deposit{value: amounts[0]}(); 313 | assert(IWETH(WETH).transfer(ElkLibrary.pairFor(factory, path[0], path[1]), amounts[0])); 314 | _swap(amounts, path, to); 315 | // refund dust ETH, if any 316 | if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); 317 | } 318 | 319 | // **** SWAP (supporting fee-on-transfer tokens) **** 320 | // requires the initial amount to have already been sent to the first pair 321 | function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { 322 | for (uint i; i < path.length - 1; i++) { 323 | (address input, address output) = (path[i], path[i + 1]); 324 | (address token0,) = ElkLibrary.sortTokens(input, output); 325 | IElkPair pair = IElkPair(ElkLibrary.pairFor(factory, input, output)); 326 | uint amountInput; 327 | uint amountOutput; 328 | { // scope to avoid stack too deep errors 329 | (uint reserve0, uint reserve1,) = pair.getReserves(); 330 | (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); 331 | amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); 332 | amountOutput = ElkLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); 333 | } 334 | (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); 335 | address to = i < path.length - 2 ? ElkLibrary.pairFor(factory, output, path[i + 2]) : _to; 336 | pair.swap(amount0Out, amount1Out, to, new bytes(0)); 337 | } 338 | } 339 | function swapExactTokensForTokensSupportingFeeOnTransferTokens( 340 | uint amountIn, 341 | uint amountOutMin, 342 | address[] calldata path, 343 | address to, 344 | uint deadline 345 | ) external virtual override ensure(deadline) { 346 | TransferHelper.safeTransferFrom( 347 | path[0], msg.sender, ElkLibrary.pairFor(factory, path[0], path[1]), amountIn 348 | ); 349 | uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); 350 | _swapSupportingFeeOnTransferTokens(path, to); 351 | require( 352 | IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 353 | 'ElkRouter: INSUFFICIENT_OUTPUT_AMOUNT' 354 | ); 355 | } 356 | function swapExactETHForTokensSupportingFeeOnTransferTokens( 357 | uint amountOutMin, 358 | address[] calldata path, 359 | address to, 360 | uint deadline 361 | ) 362 | external 363 | virtual 364 | override 365 | payable 366 | ensure(deadline) 367 | { 368 | require(path[0] == WETH, 'ElkRouter: INVALID_PATH'); 369 | uint amountIn = msg.value; 370 | IWETH(WETH).deposit{value: amountIn}(); 371 | assert(IWETH(WETH).transfer(ElkLibrary.pairFor(factory, path[0], path[1]), amountIn)); 372 | uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); 373 | _swapSupportingFeeOnTransferTokens(path, to); 374 | require( 375 | IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 376 | 'ElkRouter: INSUFFICIENT_OUTPUT_AMOUNT' 377 | ); 378 | } 379 | function swapExactTokensForETHSupportingFeeOnTransferTokens( 380 | uint amountIn, 381 | uint amountOutMin, 382 | address[] calldata path, 383 | address to, 384 | uint deadline 385 | ) 386 | external 387 | virtual 388 | override 389 | ensure(deadline) 390 | { 391 | require(path[path.length - 1] == WETH, 'ElkRouter: INVALID_PATH'); 392 | TransferHelper.safeTransferFrom( 393 | path[0], msg.sender, ElkLibrary.pairFor(factory, path[0], path[1]), amountIn 394 | ); 395 | _swapSupportingFeeOnTransferTokens(path, address(this)); 396 | uint amountOut = IERC20(WETH).balanceOf(address(this)); 397 | require(amountOut >= amountOutMin, 'ElkRouter: INSUFFICIENT_OUTPUT_AMOUNT'); 398 | IWETH(WETH).withdraw(amountOut); 399 | TransferHelper.safeTransferETH(to, amountOut); 400 | } 401 | 402 | // **** LIBRARY FUNCTIONS **** 403 | function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { 404 | return ElkLibrary.quote(amountA, reserveA, reserveB); 405 | } 406 | 407 | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) 408 | public 409 | pure 410 | virtual 411 | override 412 | returns (uint amountOut) 413 | { 414 | return ElkLibrary.getAmountOut(amountIn, reserveIn, reserveOut); 415 | } 416 | 417 | function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) 418 | public 419 | pure 420 | virtual 421 | override 422 | returns (uint amountIn) 423 | { 424 | return ElkLibrary.getAmountIn(amountOut, reserveIn, reserveOut); 425 | } 426 | 427 | function getAmountsOut(uint amountIn, address[] memory path) 428 | public 429 | view 430 | virtual 431 | override 432 | returns (uint[] memory amounts) 433 | { 434 | return ElkLibrary.getAmountsOut(factory, amountIn, path); 435 | } 436 | 437 | function getAmountsIn(uint amountOut, address[] memory path) 438 | public 439 | view 440 | virtual 441 | override 442 | returns (uint[] memory amounts) 443 | { 444 | return ElkLibrary.getAmountsIn(factory, amountOut, path); 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /contracts/elk-periphery/interfaces/IERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IERC20 { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external view returns (string memory); 8 | function symbol() external view returns (string memory); 9 | function decimals() external view returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | } 18 | -------------------------------------------------------------------------------- /contracts/elk-periphery/interfaces/IElkRouter.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.2; 2 | 3 | interface IElkRouter { 4 | function factory() external pure returns (address); 5 | function WETH() external pure returns (address); 6 | 7 | function addLiquidity( 8 | address tokenA, 9 | address tokenB, 10 | uint amountADesired, 11 | uint amountBDesired, 12 | uint amountAMin, 13 | uint amountBMin, 14 | address to, 15 | uint deadline 16 | ) external returns (uint amountA, uint amountB, uint liquidity); 17 | function addLiquidityETH( 18 | address token, 19 | uint amountTokenDesired, 20 | uint amountTokenMin, 21 | uint amountETHMin, 22 | address to, 23 | uint deadline 24 | ) external payable returns (uint amountToken, uint amountETH, uint liquidity); 25 | function removeLiquidity( 26 | address tokenA, 27 | address tokenB, 28 | uint liquidity, 29 | uint amountAMin, 30 | uint amountBMin, 31 | address to, 32 | uint deadline 33 | ) external returns (uint amountA, uint amountB); 34 | function removeLiquidityETH( 35 | address token, 36 | uint liquidity, 37 | uint amountTokenMin, 38 | uint amountETHMin, 39 | address to, 40 | uint deadline 41 | ) external returns (uint amountToken, uint amountETH); 42 | function removeLiquidityWithPermit( 43 | address tokenA, 44 | address tokenB, 45 | uint liquidity, 46 | uint amountAMin, 47 | uint amountBMin, 48 | address to, 49 | uint deadline, 50 | bool approveMax, uint8 v, bytes32 r, bytes32 s 51 | ) external returns (uint amountA, uint amountB); 52 | function removeLiquidityETHWithPermit( 53 | address token, 54 | uint liquidity, 55 | uint amountTokenMin, 56 | uint amountETHMin, 57 | address to, 58 | uint deadline, 59 | bool approveMax, uint8 v, bytes32 r, bytes32 s 60 | ) external returns (uint amountToken, uint amountETH); 61 | function swapExactTokensForTokens( 62 | uint amountIn, 63 | uint amountOutMin, 64 | address[] calldata path, 65 | address to, 66 | uint deadline 67 | ) external returns (uint[] memory amounts); 68 | function swapTokensForExactTokens( 69 | uint amountOut, 70 | uint amountInMax, 71 | address[] calldata path, 72 | address to, 73 | uint deadline 74 | ) external returns (uint[] memory amounts); 75 | function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) 76 | external 77 | payable 78 | returns (uint[] memory amounts); 79 | function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) 80 | external 81 | returns (uint[] memory amounts); 82 | function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) 83 | external 84 | returns (uint[] memory amounts); 85 | function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) 86 | external 87 | payable 88 | returns (uint[] memory amounts); 89 | 90 | function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); 91 | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); 92 | function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); 93 | function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); 94 | function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); 95 | 96 | function removeLiquidityETHSupportingFeeOnTransferTokens( 97 | address token, 98 | uint liquidity, 99 | uint amountTokenMin, 100 | uint amountETHMin, 101 | address to, 102 | uint deadline 103 | ) external returns (uint amountETH); 104 | function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( 105 | address token, 106 | uint liquidity, 107 | uint amountTokenMin, 108 | uint amountETHMin, 109 | address to, 110 | uint deadline, 111 | bool approveMax, uint8 v, bytes32 r, bytes32 s 112 | ) external returns (uint amountETH); 113 | 114 | function swapExactTokensForTokensSupportingFeeOnTransferTokens( 115 | uint amountIn, 116 | uint amountOutMin, 117 | address[] calldata path, 118 | address to, 119 | uint deadline 120 | ) external; 121 | function swapExactETHForTokensSupportingFeeOnTransferTokens( 122 | uint amountOutMin, 123 | address[] calldata path, 124 | address to, 125 | uint deadline 126 | ) external payable; 127 | function swapExactTokensForETHSupportingFeeOnTransferTokens( 128 | uint amountIn, 129 | uint amountOutMin, 130 | address[] calldata path, 131 | address to, 132 | uint deadline 133 | ) external; 134 | } 135 | -------------------------------------------------------------------------------- /contracts/elk-periphery/interfaces/IWETH.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IWETH { 4 | function deposit() external payable; 5 | function transfer(address to, uint value) external returns (bool); 6 | function withdraw(uint) external; 7 | } 8 | -------------------------------------------------------------------------------- /contracts/elk-periphery/libraries/ElkLibrary.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | import '../../elk-core/interfaces/IElkFactory.sol'; 4 | import '../../elk-core/interfaces/IElkPair.sol'; 5 | 6 | import "./SafeMath.sol"; 7 | 8 | library ElkLibrary { 9 | using SafeMath for uint; 10 | 11 | // returns sorted token addresses, used to handle return values from pairs sorted in this order 12 | function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { 13 | require(tokenA != tokenB, 'ElkLibrary: IDENTICAL_ADDRESSES'); 14 | (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); 15 | require(token0 != address(0), 'ElkLibrary: ZERO_ADDRESS'); 16 | } 17 | 18 | // calculates the CREATE2 address for a pair without making any external calls 19 | function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { 20 | (address token0, address token1) = sortTokens(tokenA, tokenB); 21 | pair = address(uint(keccak256(abi.encodePacked( 22 | hex'ff', 23 | factory, 24 | keccak256(abi.encodePacked(token0, token1)), 25 | hex'84845e7ccb283dec564acfcd3d9287a491dec6d675705545a2ab8be22ad78f31' // init code hash 26 | )))); 27 | } 28 | 29 | // fetches and sorts the reserves for a pair 30 | function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { 31 | (address token0,) = sortTokens(tokenA, tokenB); 32 | (uint reserve0, uint reserve1,) = IElkPair(pairFor(factory, tokenA, tokenB)).getReserves(); 33 | (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); 34 | } 35 | 36 | // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset 37 | function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { 38 | require(amountA > 0, 'ElkLibrary: INSUFFICIENT_AMOUNT'); 39 | require(reserveA > 0 && reserveB > 0, 'ElkLibrary: INSUFFICIENT_LIQUIDITY'); 40 | amountB = amountA.mul(reserveB) / reserveA; 41 | } 42 | 43 | // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset 44 | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { 45 | require(amountIn > 0, 'ElkLibrary: INSUFFICIENT_INPUT_AMOUNT'); 46 | require(reserveIn > 0 && reserveOut > 0, 'ElkLibrary: INSUFFICIENT_LIQUIDITY'); 47 | uint amountInWithFee = amountIn.mul(997); 48 | uint numerator = amountInWithFee.mul(reserveOut); 49 | uint denominator = reserveIn.mul(1000).add(amountInWithFee); 50 | amountOut = numerator / denominator; 51 | } 52 | 53 | // given an output amount of an asset and pair reserves, returns a required input amount of the other asset 54 | function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { 55 | require(amountOut > 0, 'ElkLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); 56 | require(reserveIn > 0 && reserveOut > 0, 'ElkLibrary: INSUFFICIENT_LIQUIDITY'); 57 | uint numerator = reserveIn.mul(amountOut).mul(1000); 58 | uint denominator = reserveOut.sub(amountOut).mul(997); 59 | amountIn = (numerator / denominator).add(1); 60 | } 61 | 62 | // performs chained getAmountOut calculations on any number of pairs 63 | function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { 64 | require(path.length >= 2, 'ElkLibrary: INVALID_PATH'); 65 | amounts = new uint[](path.length); 66 | amounts[0] = amountIn; 67 | for (uint i; i < path.length - 1; i++) { 68 | (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); 69 | amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); 70 | } 71 | } 72 | 73 | // performs chained getAmountIn calculations on any number of pairs 74 | function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { 75 | require(path.length >= 2, 'ElkLibrary: INVALID_PATH'); 76 | amounts = new uint[](path.length); 77 | amounts[amounts.length - 1] = amountOut; 78 | for (uint i = path.length - 1; i > 0; i--) { 79 | (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); 80 | amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /contracts/elk-periphery/libraries/SafeMath.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.6.6; 2 | 3 | // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) 4 | 5 | library SafeMath { 6 | function add(uint x, uint y) internal pure returns (uint z) { 7 | require((z = x + y) >= x, 'ds-math-add-overflow'); 8 | } 9 | 10 | function sub(uint x, uint y) internal pure returns (uint z) { 11 | require((z = x - y) <= x, 'ds-math-sub-underflow'); 12 | } 13 | 14 | function mul(uint x, uint y) internal pure returns (uint z) { 15 | require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /contracts/elk-periphery/libraries/UniswapV2OracleLibrary.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | import '../../elk-core/interfaces/IElkPair.sol'; 4 | import '../../elk-lib/libraries/FixedPoint.sol'; 5 | 6 | // library with helper methods for oracles that are concerned with computing average prices 7 | library ElkOracleLibrary { 8 | using FixedPoint for *; 9 | 10 | // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] 11 | function currentBlockTimestamp() internal view returns (uint32) { 12 | return uint32(block.timestamp % 2 ** 32); 13 | } 14 | 15 | // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. 16 | function currentCumulativePrices( 17 | address pair 18 | ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { 19 | blockTimestamp = currentBlockTimestamp(); 20 | price0Cumulative = IElkPair(pair).price0CumulativeLast(); 21 | price1Cumulative = IElkPair(pair).price1CumulativeLast(); 22 | 23 | // if time has elapsed since the last update on the pair, mock the accumulated price values 24 | (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IElkPair(pair).getReserves(); 25 | if (blockTimestampLast != blockTimestamp) { 26 | // subtraction overflow is desired 27 | uint32 timeElapsed = blockTimestamp - blockTimestampLast; 28 | // addition overflow is desired 29 | // counterfactual 30 | price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; 31 | // counterfactual 32 | price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /elk-interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elkfinance/exchange-contracts/78a554d4aa7de35c5c80d4964e5088860ad64c3a/elk-interface.png -------------------------------------------------------------------------------- /hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomiclabs/hardhat-waffle"); 2 | require("@nomiclabs/hardhat-ethers"); 3 | 4 | // This is a sample Hardhat task. To learn how to create your own go to 5 | // https://hardhat.org/guides/create-task.html 6 | task("accounts", "Prints the list of accounts", async () => { 7 | const accounts = await ethers.getSigners(); 8 | 9 | for (const account of accounts) { 10 | console.log(account.address); 11 | } 12 | }); 13 | 14 | /** 15 | * @type import('hardhat/config').HardhatUserConfig 16 | */ 17 | module.exports = { 18 | solidity: { 19 | compilers: [ 20 | { 21 | version: "0.5.16" 22 | }, 23 | { 24 | version: "0.6.2" 25 | }, 26 | { 27 | version: "0.6.6", 28 | settings: { 29 | optimizer: { 30 | enabled: true, 31 | runs: 1000 32 | } 33 | } 34 | }, 35 | { 36 | version: "0.7.0" 37 | }, 38 | { 39 | version: "0.8.0" 40 | } 41 | ] 42 | }, 43 | networks: { 44 | hardhat: { 45 | gasPrice: 470000000000, 46 | chainId: 43112, 47 | initialDate: "2020-10-10", 48 | }, 49 | avash: { 50 | url: 'http://localhost:9650/ext/bc/C/rpc', 51 | gasPrice: 470000000000, 52 | chainId: 43112, 53 | accounts: ["0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027"] 54 | }, 55 | fuji: { 56 | url: 'https://api.avax-test.network/ext/bc/C/rpc', 57 | gasPrice: 470000000000, 58 | chainId: 43113, 59 | accounts: [] 60 | }, 61 | mainnet: { 62 | url: 'https://api.avax.network/ext/bc/C/rpc', 63 | gasPrice: 470000000000, 64 | chainId: 43114, 65 | accounts: [] 66 | } 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@elkdex/eth-exchange-contracts", 3 | "publishConfig": { 4 | "access": "public" 5 | }, 6 | "devDependencies": { 7 | "@nomiclabs/hardhat-ethers": "^2.0.1", 8 | "@nomiclabs/hardhat-waffle": "^2.0.1", 9 | "chai": "^4.2.0", 10 | "ethereum-waffle": "^3.2.1", 11 | "ethereumjs-tx": "^2.1.2", 12 | "ethers": "^5.0.24", 13 | "hardhat": "^2.0.6" 14 | }, 15 | "version": "1.0.0", 16 | "description": "Contracts for the Elk Dex on MATIC.", 17 | "main": "index.js", 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/elkfinance/eth-exchange-contracts.git" 21 | }, 22 | "author": "Team Elk ", 23 | "license": "MIT", 24 | "scripts": { 25 | "precompile": "rimraf ./build/", 26 | "compile": "npx hardhat compile", 27 | "pretest": "yarn compile", 28 | "test": "npx hardhat test", 29 | "lint": "prettier ./test/**/*.ts --check", 30 | "prepublishOnly": "yarn test" 31 | }, 32 | "bugs": { 33 | "url": "https://github.com/elkfinance/eth-exchange-contracts/issues" 34 | }, 35 | "homepage": "https://elk.finance" 36 | } 37 | --------------------------------------------------------------------------------