[
  {
    "path": ".gitattributes",
    "content": "*.sol linguist-language=Solidity\n"
  },
  {
    "path": ".gitignore",
    "content": "/out\nload-env*\nload-fab*\naddresses.json\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"lib/ds-test\"]\n\tpath = lib/ds-test\n\turl = https://github.com/dapphub/ds-test\n[submodule \"lib/ds-token\"]\n\tpath = lib/ds-token\n\turl = https://github.com/dapphub/ds-token\n[submodule \"lib/ds-thing\"]\n\tpath = lib/ds-thing\n\turl = https://github.com/dapphub/ds-thing\n[submodule \"lib/ds-value\"]\n\tpath = lib/ds-value\n\turl = https://github.com/dapphub/ds-value\n[submodule \"lib/ds-guard\"]\n\tpath = lib/ds-guard\n\turl = https://github.com/dapphub/ds-guard\n[submodule \"lib/ds-roles\"]\n\tpath = lib/ds-roles\n\turl = http://github.com/dapphub/ds-roles\n[submodule \"lib/ds-chief\"]\n\tpath = lib/ds-chief\n\turl = https://github.com/dapphub/ds-chief\n[submodule \"lib/ds-spell\"]\n\tpath = lib/ds-spell\n\turl = https://github.com/dapphub/ds-spell\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "DEVELOPING.md",
    "content": "# Sai Developer Documentation\n\nThis is a developer level guide to the Sai source layout and how the\ndifferent objects relate to each other.\n\n\n## Introduction\n\nSai is Simple-Dai, a simplification of the Dai Stablecoin System\nintended for field testing and refining Dai components. Sai has several\nfeatures that distinguish it from Dai:\n\n- trusted price feed\n- single collateral type\n- global settlement\n- liquidations at fixed price (rather than auctions)\n\nThis document is an introduction to Sai, aimed at those seeking an\nunderstanding of the Solidity implementation.  We assume knowledge of\nthe [white paper], a high level overview of Dai.  A reading of the\n[purple paper], the (in progress) detailed Dai technical specification\nand reference implementation, is strongly encouraged but not required.\n\n[white paper]: https://github.com/makerdao/docs/blob/master/Dai.md\n[purple paper]: https://makerdao.com/purple\n\n\n## Overview\n\nSai uses the following tokens:\n\n- `gem`: underlying collateral (wrapped ether, in practice)\n- `skr`: abstracted collateral claim\n- `sai`: stablecoin\n- `sin`: anticoin, created when the system takes on debt\n\nSai has the following core components:\n\n- `vox`: target price feed\n- `tub`: CDP record store\n- `tap`: liquidation mechanism\n- `top`: global settlement facilitator\n\nSai is configured by the following 'risk parameters':\n\n- `way`: Sai reference price drift\n- `cap`: Debt ceiling\n- `mat`: Liquidation ratio\n- `tax`: Stability fee\n- `axe`: Liquidation penalty\n- `gap`: Join/Exit and Boom/Bust spread\n\n\n\n### `skr`: A Token Wrapper\n\n`skr` is a token wrapper.\n\n- `join`: deposit `gem` in return for `skr`\n- `exit`: claim `gem` with their `skr`.\n\n![Join-Exit](https://user-images.githubusercontent.com/5028/30517891-928dd4d8-9bc1-11e7-9398-639233d851ae.png)\n\n`skr` is a simple proportional claim on a collateral pool, with the\ninitial `gem`<->`skr` exchange ratio being 1:1.  The essential reason\nfor this abstraction will be developed later, but for now it is\nsufficient to see `skr` as a token with intrinsic value.\n\nThe `gem`/`skr` exchange rate is called `per`, and is calculated as the\ntotal number of deposited `gem` divided by the total supply of SKR.\n\nThe reference price of `gem` (in practice, ETHUSD) is provided by the\n`pip`, an external oracle. The `pip` is completely trusted.\n\nThe reference price of `skr` is then given by the dynamic `tag`, e.g.\nthe price of SKR in USD.\n\n\n### `vox`: Target Price Feed\n\nThe `vox` provides the Sai *target price*, given in terms of the\nreference unit, by `par`. For example, `par == 2` with USD as the\nreference unit implies a target price of 2 USD per Sai.\n\nThe target price can vary in time, at a rate given by `way`, which is\nthe multiplicative rate of change per second.\n\nThe `vox` is the same as that in Dai, but with the sensitivity, `how`,\nset to zero. Adjustments to the target price are made by adjusting the\nrate of change, `way`, directly with `coax`. In future Sai iterations,\n`how` may be non-zero and `way` adjustments will then follow\nautomatically via the feedback mechanism. The `vox` component is subject\nto ongoing economic modelling research.\n\n\n### `tub`: CDP Record Engine\n\nThe `tub` is the CDP record system.  An individual CDP is called a `cup`\n(i.e. a small container), and has:\n\n- `lad`: an owner\n- `ink`: locked SKR collateral\n- `art`: debt\n\nIt is crucial to know whether a CDP is well collateralised or not:\n`safe(cup)` returns a boolean indicating this.\n\n`safe` aggregates price information from the `vox` and the `tub` and\ncompares the reference value of a CDPs debt and collateral.\n\nThe following `tub` acts are not possible if they would transition a CDP\nto unsafe:\n\n---\n\n![Open | Give](https://user-images.githubusercontent.com/5028/30352570-b4c0f6a2-9874-11e7-8ca3-336531da4c0d.png)\n\n- `open`: create a new CDP\n- `give`: transfer ownership (changes `lad`)\n---\n\n![Lock-Free](https://user-images.githubusercontent.com/5028/30517892-928e06ec-9bc1-11e7-91e8-6ae6caae8585.png)\n\n\n- `lock`: deposit SKR collateral (increases `ink`)\n- `free`: withdraw SKR collateral (decreases `ink`)\n\n---\n\n![Draw | Wipe](https://user-images.githubusercontent.com/5028/30463893-97a6aef4-9a22-11e7-9a65-3055ad05b8d6.png)\n\n- `draw`: create Sai (increases `art`, `rum`)\n- `wipe`: return Sai (decreases `art`, `rum`)\n\n---\n\n- `shut`: clear all CDP debt, unlock all collateral, and delete the record\n\n---\n\n<img src=\"https://user-images.githubusercontent.com/5028/30519068-6c871ed2-9be1-11e7-83df-3cbda6a49e3b.png\" width=\"600\" />\n\n- `bite`: liquidate CDP (zeros `art`, decreases `ink`, mints `sin` to `tap`)\n\nUnsafe CDPs need to be liquidated. When a `cup` is not `safe`, anyone\ncan perform `bite(cup)`, which takes on all CDP debt and confiscates\nsufficient collateral to cover this, plus a buffer.\n\nThis returns the CDP to a safe state (possibly with zero collateral).\nThere are other possible implementations of `bite`, e.g. only taking\nsufficient collateral to just transition the CDP to safe, but the\ndescribed implementation is chosen for simplicity.\n\n`bite` mints the `sin` associated with the CDP to the `tap` - the\nliquidator.\n\n---\n\n\n### `tap`: The Liquidator\n\nThe `tap` is a liquidator. It has three token balances that determine\nits allowed behaviour:\n\n- `joy`: Sai balance, surplus transferred from `drip`\n- `woe`: Sin balance, bad debt transferred from `bite`\n- `fog`: SKR balance, collateral pending liquidation\n\nand one derived price, `s2s`, which is the price of SKR in Sai. The\n`tap` seeks to minimise all of its token balances. Recall that Sai can\nbe canceled out with Sin via `heal`.\n\nThe `tap` has two acts:\n\n- `boom`: sell Sai in return for SKR (decreases `joy` and `woe`, decreases SKR supply)\n- `bust`: sell SKR in return for Sai (decreases `fog`, increases `joy` and `woe`, can increase SKR supply)\n\n`boom` is the simpler function and can be thought of as buy and burn.\nGiven a net Sai balance, sell the Sai in return for SKR, which is\nburned.\n\n<img src=\"https://user-images.githubusercontent.com/5028/30517887-924bec1c-9bc1-11e7-8c25-6d73a1c48340.png\" width=\"500\" />\n\n`bust` is really two functions in one: collateral sell off (aka `flip`),\nand inflate and sell (aka `flop`). When `fog` is non zero it is sold in\nreturn for Sai, which is used to cancel out the bad debt, `woe`. If\n`fog` is zero but the `tap` has a net Sin balance, then SKR is minted\nand sold in return for Sai, up to the point that the net Sin balance is\nzero.\n\n![Bust](https://user-images.githubusercontent.com/5028/30517888-9287dd76-9bc1-11e7-8726-6b21843e27a5.png)\n\nThrough `boom` and `bust` we close the feedback loop on the price of\nSKR. When there is surplus Sai, SKR is burned, decreasing the SKR supply\nand increasing `per`, giving SKR holders more GEM per SKR. When there is\nsurplus Woe, SKR is inflated, increasing the SKR supply and decreasing\n`per`, giving SKR holders less GEM per SKR.\n\nThe reason for wrapping GEM in SKR is now apparent: *it provides a way\nto socialise losses and gains incurred in the operation of the system.*\n\nTwo features of this mechanism:\n\n1. Whilst SKR can be inflated significantly, there is a finite limit on\n   the amount of bad debt the system can absorb - given by the value of\n   the underlying GEM collateral.\n\n2. There is a negative feedback between `bust` and `bite`: as SKR is\n   inflated it becomes less valuable, reducing the safety level of CDPs.\n   Some CDPs will become unsafe and be vulnerable to liquidation,\n   creating more bad debt. In an active market, CDP holders will have to\n   be vigilant about the potential for SKR inflation if they are holding\n   tightly collateralised CDPs.\n\n\n### `top`: Global Settlement Manager\n\nA key feature of Sai is the possibility of `cage`: shutting down the\nsystem and reimbursing Sai holders. This is provided for easy upgrades\nbetween Sai iterations, and for security in case of implementation flaws\n- both in the code and in the design.\n\nAn admin can use the `top` to `cage` the system at a specific price (sai\nper gem), or by reading the last price from the price feed.\n\n<img src=\"https://user-images.githubusercontent.com/5028/30519069-6c9ae656-9be1-11e7-9e3f-e75f585024f7.png\" width=\"600\" />\n\nFirst, sufficient real `gem` collateral is taken such that Sai holders\ncan redeem their Sai at face value. The `gem` is moved from the `tub` to\nthe `tap` and the `tap.cash` function is unlocked for Sai holders to\ncall.\n\n![Cash](https://user-images.githubusercontent.com/5028/30519070-6cc4fd6a-9be1-11e7-92d8-5d965721d8ef.png)\n\nAny remaining `gem` remains in the `tub`. SKR holders can now `exit`.\nCDP holders must first `bite` their CDPs (although anyone can do this)\nand then `free` their SKR.\n\nSome important features of `cage`:\n\n- Sai holders are not guaranteed their face value, only preferential payout.\n- *the full real collateral pool is tapped* to make Sai whole. SKR is a\n  *risk-bearing* token.\n- SKR holders will receive a poor rate if they try to `exit` before all\n  CDPs are processed by `bite`. To prevent accidental early `exit`,\n  `top.flow` is provided, which will only enable `exit` after all CDPs\n  are processed, or a timeout has expired.\n\nThe `top` also serves as a useful frontend entrypoint to the system, as it\nlinks to all other components.\n\n### `drip`, `rum`, `art` and `chi`: Dynamic Fee Accumulation\n\nIn a simpler system with no interest rates, we could denominate CDP debt,\nthe `tab`, directly in `sin`. However with non zero interest, `tab` is a\ndynamic quantity, computed from `art`, a rate-normalised per-CDP debt unit,\nand `chi`, the product of accumulated rates that converts `art` into a real\ndebt amount. `rum` is the total `art` across all CDPs, and can be used\nto determine the total debt backed by CDPs, `din`.\n\n```\ntab(cdp) = cdp.art * chi\n```\n\nThe internal debt price, `chi`, is dynamic and is updated by the `drip`\nact, which also collects unprocessed revenue.\n\nThe `chi` abstraction allows us to compute the per CDP debt, and the\ntotal unprocessed revenue, with varying `tax`, in constant time.\n\n<img src=\"https://user-images.githubusercontent.com/5028/30517890-928d0094-9bc1-11e7-936c-544f5bc4d197.png\" width=\"600\" />\n\n## Governance Fee\n\nThis version of Sai (aka Dai v1) is collectively governed by the holders of\na token, `gov`. The specifics of the governance mechanism are\nout of scope for this document. The `gov` token is also used to pay usage\nfees: the `fee` is similar to the `tax`, and causes the `rhi` accumulator to\nincrease relative to `chi`. The difference between `rhi` and `chi` can be\nused to determine the total outstanding fee, the `rap`. Fees are paid on\n`wipe`, and the amount payable is scaled with the amount wiped.\n\nFees are paid in `gov`, but the outstanding fee is denominated in Sai.\nTherefore we need a price feed for `gov`: this is the `pep`. The mechanism\nin `wipe` is meant to be robust against failure of the `pep` feed.\n\nImportantly, unpaid fees _are not_ used to determine a CDPs safety (this may\nchange in a future release).\n\n\n## Auth setup\n\nSai is designed with two authorities, `dad` and `chief`.\n\n- `dad` is a DSGuard, and is used for internal contract-contract\n  permissions, allowing e.g. the `tub` to `mint` and `burn` Sai. `dad`\n  is the authority of the `tub` and `tap`, and also `sai`, `sin` and\n  `skr`.\n\n- `chief` restricts access to `top` and `mom`, which are the admin\n  interfaces to the system. `chief` is intended to be a DSRoles\n  instance, but any authority implementation could be used.\n\n\n## Deployment\n\nSai is a complex multi-contract system and has a slightly involved\ndeployment process. The prerequisities to the deployment are:\n\n1. `pip`, a collateral price feed\n2. `pep`, a governance price feed\n3. `gem`, a collateral token\n4. `pit`, a token burner\n5. `chief`, the external authority\n\nFor testing purposes, `bin/deploy` will create the prerequisites for you\nif you don't supply them.\n\nIn addition, Sai utilises on-chain deployers, called fabs, for creating\nfresh basic components on chain. These are defined in `fab.sol`.\n\nThe main contract deployment is defined in `DaiFab`, and requires\nmultiple calls because of the size of the contracts.\n\nThe full contracts can be deployed to e.g.  ethlive with the following,\nafter which the contract addresses will be saved in `load-env-ethlive`.\n\n```\nbin/deploy-fab\n. load-fab-ethlive\nbin/deploy\n```\n\n\n## Glossary\n\n### Prices\n\n- `per`: gem per skr\n- `par`: ref per sai\n- `tag`: ref per skr\n- `pip`: ref per gem\n- `fix`: gem per sai after `cage`\n- `fit`: ref per skr after `cage`\n\n### Meme Mnemonics\n\n- `pip`: trading pips\n- `cup`: small container for CDP info\n- `tub`: larger container for cups\n- `tap`: liquidity provider\n- `top`: top-level system manager\n\n- `way`: which way the target price is heading\n- `cap`: upper limit of Sai issuance\n- `mat`: lower limit of collateralisation\n- `tax`: continually paid by CDP holders\n- `axe`: penalty applied to bad CDP holders\n- `gap`: gap between buy and sell\n\n- `pie`: Real collateral that SKR holders share\n- `air`: Abstracted Collateral backing CDPs\n- `ice`: Debt that is locked up with CDPs\n- `fog`: Murky liquidated `air`that we want to get rid of\n- `joy`: SKR holders are happy about this Sai surplus\n- `woe`: SKR holders are sad about this Sin debt\n"
  },
  {
    "path": "Makefile",
    "content": "all:; dapp build\ntest:; dapp test\n\nSHELL = bash\ndirs = {bin,libexec}\nprefix ?= /usr/local\n\ndirs:; mkdir -p $(prefix)/$(dirs)\nfiles = $(shell ls -d $(dirs)/*)\ninstall:; cp -r -n $(dirs) $(prefix)\nlink: dirs; for x in $(files); do ln -s `pwd`/$$x $(prefix)/$$x; done\nuninstall:; rm -r $(addprefix $(prefix)/,$(files))\n\ncheck:; ! grep '^#!/bin/sh' libexec/*/* && \\\ngrep '^#!/usr/bin/env bash' libexec/*/* | \\\ncut -d: -f1 | xargs shellcheck\n"
  },
  {
    "path": "README.md",
    "content": "\n\n\n_Please note that this document temporarily refers to sai instead of dai and skr instead of peth. These are just different variable names and their functionality is identical to what is described in the latest Dai documentation._\n\n\n`sai` is a simple single-collateral stablecoin that is dependent on a\ntrusted oracle address and has a kill-switch.\n\nSee the [developer documentation](DEVELOPING.md) for a more technical\noverview.\n\nThere are four tokens in the system:\n\n- `gem`: externally valuable token e.g. ETH\n- `gov`: governance token e.g. MKR\n- `skr`: a claim to locked `gem`s\n- `sai`: the stablecoin, a variable claim on some quantity of `gem`s\n\nCollateral holders deposit their collateral using `join` and receive\n`skr` tokens proportional to their deposit. `skr` can be redeemed for\ncollateral with `exit`. You will get more or less `gem` tokens for each\n`skr` depending whether the system made a profit or loss while you\nwere exposed.\n\nThe oracle updates the GEM:REF and GOV:REF price feeds. These are the\nonly external real-time input to the system.\n\n`skr` is used as the direct backing collateral for CDPs. A prospective\nissuer can `open` an empty position, `lock` some `skr` and then `draw`\nsome `sai`. Debt is covered with `wipe`. Collateral can be reclaimed\nwith `free` as long as the CDP remains \"safe\".\n\nIf the value of the collateral backing the CDP falls below the\nliquidation ratio `mat`, the CDP is vulnerable to liquidation via\n`bite`. On liquidation, the CDP `skr` collateral is sold off to cover\nthe `sai` debt.\n\nUnder-collateralized CDPs can be liquidated with `bite`. Liquidation is\nimmediate: backing `skr` is taken to cover the `sai` debt at the time of\n`bite`, plus a liquidation fee (`axe`); any excess remains in the CDP.\n\n`skr` seized from bad CDPs can be purchased with `bust`, in exchange for\n`sai` at the `s2s` price. This `sai` pays down the bad CDP debt.\n\nAny remaining Sai surplus (`joy`) can be purchased with `boom`, in\nexchange for `skr` at the `s2s` price. This `skr` is burned.\n\n\n### Fees\n\nStability fee is continuously charged on all open cups according to `tax`.\nIt makes their debt (`tab`) increase over time.\n\nGovernance fee is continuously charged on all open cups according to `fee`.\nIt makes their debt (`rap`) increase over time.\n\n### Settlement\n\n`sai` can be shut down at a given price with `cage`, after which `sai`\nand `skr` can be exchanged for `gems` via `cash`. All outstanding `cups`\nare liquidated and the *entire pool* of `gem` is tapped to redeem `sai`\nat their face value, as if the boom/bust trades were instantly settled\nat the cage price.  Any remaining `gems` are shared between `skr`\nholders.\n\nPractically this means that if the system is undercollateralized on\n`cage`, holders of free `skr` will have their `gem` share diluted as\nmuch as necessary to make `sai` whole. *In other words, `skr` is a\nrisk bearing token*.\n\nExcess collateral contained within a single `cup` can be reclaimed with\n`bite(cup)`.\n\n\n### `sai` glossary (`sai help`)\n```\nActions:\n\n   bite            initiate liquidation of an undercollateral cup\n   boom            buy some amount of sai to process joy (surplus)\n   bust            sell some amount of sai to process woe (bad debt)\n   cage            lock the system and initiate settlement\n   cash            cash in sai balance for gems after cage\n   cupi            get the last cup id\n   cups            list cups created by you\n   draw            issue the specified amount of sai stablecoins\n   drip            recalculate the internal debt price\n   exit            sell SKR for gems\n   free            remove excess SKR collateral from a cup\n   give            transfer ownership of a cup\n   heal            cancel debt\n   help            print help about sai(1) or one of its subcommands\n   join            buy SKR for gems\n   lock            post additional SKR collateral to a cup\n   open            create a new cup (collateralized debt position)\n   prod            recalculate the accrued holder fee (par)\n   safe            determine if a cup is safe\n   setAxe          update the liquidation penalty\n   setFee          update the governance fee\n   setCap          update the debt ceiling\n   setMat          update the liquidation ratio\n   setTapGap       update the spread on `boom` and `bust`\n   setTax          update the stability fee\n   setTubGap       update the spread on `join` and `exit`\n   setWay          update the holder fee (interest rate)\n   shut            close a cup\n   vent            process a caged tub\n   wipe            repay some portion of your existing sai debt\n   \nVars, Getters, Utils:\n\n   air             get the amount of backing collateral\n   axe             get the liquidation penalty\n   caged           get time of cage event (= 0 if system is not caged)\n   chi             get the internal debt price\n   cup             show the cup info\n   fee             get the governance fee\n   fit             get the gem per skr settlement price\n   fix             get the gem per sai settlement price\n   fog             get the amount of skr pending liquidation\n   gem             get the collateral token\n   gov             get the governance token\n   cap             get the debt ceiling\n   ice             get the good debt\n   ink             get the amount of skr collateral locked in a cup\n   joy             get the amount of surplus sai\n   lad             get the owner of a cup\n   mat             get the liquidation ratio\n   off             get the cage flag\n   out             get the post cage exit flag\n   par             get the accrued holder fee (ref per sai)\n   per             get the current entry price (gem per skr)\n   pie             get the amount of raw collateral\n   pep             get the gov price feed\n   pip             get the gem price feed\n   pit             get the liquidator vault\n   rap             get the amount of governance debt in a cup\n   ray             parse and display a 27-decimal fixed-point number\n   rho             get the time of last drip\n   rhi             get the internal debt price (governance included)\n   s2s             get the skr per sai rate (for boom and bust)\n   sai             get the sai token\n   sin             get the sin token\n   skr             get the skr token\n   tab             get the amount of debt in a cup\n   tag             get the reference price (ref per skr)\n   tapAsk          get the amount of skr in sai for bust\n   tapBid          get the amount of skr in sai for boom\n   tapGap          get the spread on `boom` and `bust`\n   tau             get the time of last prod\n   tax             get the stability fee\n   tubAsk          get the amount of skr in gem for join\n   tubBid          get the amount of skr in gem for exit\n   tubGap          get the spread on `join` and `exit`\n   vox             get the target price engine\n   wad             parse and display a 18-decimal fixed-point number\n   way             get the holder fee (interest rate)\n   woe             get the amount of bad debt\n\n\n```\n\n### Sample interaction using `sai`\n\n```bash\n$ export ETH_FROM=0x(...)\n$ export SAI_TUB=0x(...)\n\n# Give the system access to our GEM (W-ETH), SKR and SAI balances\n# so we can join()/exit() and also draw()/wipe() sai\n$ token approve $(sai gem) $(sai tub) $(seth --to-wei 1000000000 ETH)\n$ token approve $(sai skr) $(sai tub) $(seth --to-wei 1000000000 ETH)\n$ token approve $(sai sai) $(sai tub) $(seth --to-wei 1000000000 ETH)\n\n# If we also plan on using boom() and bust(), a different component\n# (called `tap`) will need to have access to our SKR and SAI balances\n$ token approve $(sai skr) $(sai tap) $(seth --to-wei 1000000000 ETH)\n$ token approve $(sai sai) $(sai tap) $(seth --to-wei 1000000000 ETH)\n\n# We need to have some GEM (W-ETH) balance to start with\n$ token balance $(sai gem) $ETH_FROM\n2.467935274974511817\n\n# Join the system by exchanging some GEM (W-ETH) to SKR\n$ sai join 2.2\nGenerating 2.200000000000000000 SKR depositing GEM...\n$ token balance $(sai gem) $ETH_FROM\n0.267935274974511817\n$ token balance $(sai skr) $ETH_FROM\n2.200000000000000000\n\n# Open a new cup\n$ sai open\nOpening cup...\nOpened cup 62\n\n# We can list our cups at all times\n$ sai cups\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\nCups created by you...\n62\n\n# Lock some SKR collateral in the cup and then draw some SAI from it\n$ sai --cup 62 lock 1.5\t\t\t\t\t\t\t\t\t\t\t\t\t\nLocking 1.500000000000000000 SKR in cup 62...\n$ sai --cup 62 draw 89.0\t\t\t\t\t\t\t\t\t\t\t\t\nDrawing 89.000000000000000000 SAI from cup 62...\n$ token balance $(sai skr) $ETH_FROM\n0.700000000000000000\n$ token balance $(sai sai) $ETH_FROM\n89.000000000000000000\n\n# We can examine the cup details, `tab` and `ink` representing\n# the amount of debt and the amount of collateral respectively\n$ sai --cup 62 cup\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ncup id 62...\nlad: 0x(...)\nink: 1.500000000000000000\ntab: 89.000000000000000000\nrap: 0.000000000000000000\n\n# We can check whether the cup is still safe\n# (ie. whether the value of collateral locked is high enough)\n$ sai --cup 62 safe\ntrue\n\n# At some point we will want to wipe our SAI debt\n# which means we can also free the SKR collateral\n$ sai --cup 62 wipe 59.0\t\t\t\t\t\t\t\t\t\t\t\t\nWiping 59.000000000000000000 SAI from cup 62...\n$ sai --cup 62 free 1.1\t\t\t\t\t\t\t\t\t\t\t\t\t\nFreeing 1.100000000000000000 SKR from cup 62...\n$ token balance $(sai skr) $ETH_FROM\n1.800000000000000000\n$ token balance $(sai sai) $ETH_FROM\n30.000000000000000000\n\n# The `tab` and `ink` values have changed\n$ sai --cup 62 cup\ncup id 62...\nlad: 0x(...)\nink: 0.400000000000000000\ntab: 30.000000000000000000\nrap: 0.000000000000000000\n\n# We can also `wipe` and `free` outstanding balances of SAI and SKR by calling `shut`\n$ sai --cup 62 shut\nClosing cup 62...\n\n$ sai --cup 62 cup\ncup id 62...\nlad: 0x0000000000000000000000000000000000000000\nink: 0.000000000000000000\ntab: 0.000000000000000000\nrap: 0.000000000000000000\n\n# Exit the system by exchanging SKR back to GEM (W-ETH)\n$ sai exit 2.2\nSending 2.200000000000000000 SKR to TUB...\n$ token balance $(sai gem) $ETH_FROM\n2.467935274974511817\n$ token balance $(sai skr) $ETH_FROM\n0.000000000000000000\n```\n\n### Dai v1 Current deployments\n\nNames for tokens:\n  - Dai: `SAI_SAI`\n  - MKR: `SAI_GOV`\n  - WETH: `SAI_GEM`\n  - PETH: `SAI_SKR`\n\nMainnet:\n\n```bash\n# sai deployment on ethlive from c2031c0f9f3a186e90b6a3c1905282f7cc58b9f5\n# Mon 18 Dec 03:12:57 GMT 2017\n# SAI_ADM updated 2019-06-11\n\nexport SAI_GEM=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\nexport SAI_GOV=0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2\nexport SAI_PIP=0x729D19f657BD0614b4985Cf1D82531c67569197B\nexport SAI_PEP=0x99041F808D598B782D5a3e498681C2452A31da08\nexport SAI_PIT=0x69076e44a9c70a67d5b79d95795aba299083c275\nexport SAI_ADM=0x9eF05f7F6deB616fd37aC3c959a2dDD25A54E4F5\nexport SAI_SAI=0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359\nexport SAI_SIN=0x79f6d0f646706e1261acf0b93dcb864f357d4680\nexport SAI_SKR=0xf53ad2c6851052a81b42133467480961b2321c09\nexport SAI_DAD=0x315cbb88168396d12e1a255f9cb935408fe80710\nexport SAI_MOM=0xf2c5369cffb8ea6284452b0326e326dbfdcb867c\nexport SAI_VOX=0x9b0f70df76165442ca6092939132bbaea77f2d7a\nexport SAI_TUB=0x448a5065aebb8e423f0896e6c5d525c040f59af3\nexport SAI_TAP=0xbda109309f9fafa6dd6a9cb9f1df4085b27ee8ef\nexport SAI_TOP=0x9b0ccf7c8994e19f39b2b4cf708e0a7df65fa8a3\n```\n\nKovan:\n\n```bash\n\n# sai deployment on kovan from 7d9c16c056c9fc99cdf2f17bc7958837cd17ee41\n# Wed Jan  3 16:06:26 -03 2018\n\nexport SAI_GEM=0xd0a1e359811322d97991e03f863a0c30c2cf029c\nexport SAI_GOV=0xaaf64bfcc32d0f15873a02163e7e500671a4ffcd\nexport SAI_PIP=0xa944bd4b25c9f186a846fd5668941aa3d3b8425f\nexport SAI_PEP=0x02998f73fabb52282664094b0ff87741a1ce9030\nexport SAI_PIT=0xbd747742b0f1f9791d3e6b85f8797a0cf4fbf10b\nexport SAI_ADM=0x74d41fd874234d9bea31ff6b090ba1d0b9dc8785\nexport SAI_SAI=0xc4375b7de8af5a38a93548eb8453a498222c4ff2\nexport SAI_SIN=0xdcdca4371befceafa069ca1e2afd8b925b69e57b\nexport SAI_SKR=0xf4d791139ce033ad35db2b2201435fad668b1b64\nexport SAI_DAD=0x6a884c7af48e29a20be9ff04bdde112b5596fcee\nexport SAI_MOM=0x72ee9496b0867dfe5e8b280254da55e51e34d27b\nexport SAI_VOX=0xbb4339c0ab5b1d9f14bd6e3426444a1e9d86a1d9\nexport SAI_TUB=0xa71937147b55deb8a530c7229c442fd3f31b7db2\nexport SAI_TAP=0xc936749d2d0139174ee0271bd28325074fdbc654\nexport SAI_TOP=0x5f00393547561da3030ebf30e52f5dc0d5d3362c\n```\n"
  },
  {
    "path": "bin/deploy",
    "content": "#!/usr/bin/env bash\nset -ex\n\nexport SOLC_FLAGS=${SOLC_FLAGS:-\"--optimize\"}\nexport ETH_GAS=${ETH_GAS:-\"4500000\"}\nexport ETH_FROM=${ETH_FROM:-$(seth rpc eth_coinbase)}\n\ndapp --use solc:0.4.25 build --extract\n\n# shellcheck disable=SC2153\n{ test -z \"$GEM_FAB\"    || test -z \"$VOX_FAB\"     || test -z \"$TUB_FAB\" || \\\n  test -z \"$TAP_FAB\"    || test -z \"$TOP_FAB\"     || test -z \"$MOM_FAB\" || \\\n  test -z \"$DAD_FAB\"; } && \\\n  exit 1\n\ntest -z \"$SAI_GEM\" && SAI_GEM=$(dapp create DSToken \"$(seth --to-bytes32 \"$(seth --from-ascii 'ETH')\")\")\ntest -z \"$SAI_GOV\" && SAI_GOV=$(dapp create DSToken \"$(seth --to-bytes32 \"$(seth --from-ascii 'GOV')\")\")\ntest -z \"$SAI_PIP\" && SAI_PIP=$(dapp create DSValue)\ntest -z \"$SAI_PEP\" && SAI_PEP=$(dapp create DSValue)\ntest -z \"$SAI_PIT\" && SAI_PIT=\"0x0000000000000000000000000000000000000123\"\n\nDAI_FAB=$(dapp create DaiFab \"$GEM_FAB\" \"$VOX_FAB\" \"$TUB_FAB\" \"$TAP_FAB\" \"$TOP_FAB\" \"$MOM_FAB\" \"$DAD_FAB\")\n\nif [ -z \"$SAI_ADM\" ]\nthen\n    SAI_ADM=$(dapp create DSRoles)\n    seth send \"$SAI_ADM\" 'setRootUser(address,bool)' \"$ETH_FROM\" true\nfi\n\nseth send \"$DAI_FAB\" 'makeTokens()'\nseth send \"$DAI_FAB\" 'makeVoxTub(address,address,address,address,address)' \"$SAI_GEM\" \"$SAI_GOV\" \"$SAI_PIP\" \"$SAI_PEP\" \"$SAI_PIT\"\nseth send \"$DAI_FAB\" 'makeTapTop()'\nseth send \"$DAI_FAB\" 'configParams()'\nseth send \"$DAI_FAB\" 'verifyParams()'\nseth send \"$DAI_FAB\" 'configAuth(address)' \"$SAI_ADM\"\n\nSAI_SAI=0x$(seth call \"$DAI_FAB\" 'sai()(address)')\nSAI_SIN=0x$(seth call \"$DAI_FAB\" 'sin()(address)')\nSAI_SKR=0x$(seth call \"$DAI_FAB\" 'skr()(address)')\nSAI_DAD=0x$(seth call \"$DAI_FAB\" 'dad()(address)')\nSAI_MOM=0x$(seth call \"$DAI_FAB\" 'mom()(address)')\nSAI_VOX=0x$(seth call \"$DAI_FAB\" 'vox()(address)')\nSAI_TUB=0x$(seth call \"$DAI_FAB\" 'tub()(address)')\nSAI_TAP=0x$(seth call \"$DAI_FAB\" 'tap()(address)')\nSAI_TOP=0x$(seth call \"$DAI_FAB\" 'top()(address)')\n\ncat > \"load-env-$(seth chain)\" << EOF\n#!/bin/bash\n\n# sai deployment on $(seth chain) from $(git rev-parse HEAD)\n# $(date)\n\nexport SAI_GEM=$SAI_GEM\nexport SAI_GOV=$SAI_GOV\nexport SAI_PIP=$SAI_PIP\nexport SAI_PEP=$SAI_PEP\nexport SAI_PIT=$SAI_PIT\nexport SAI_ADM=$SAI_ADM\nexport SAI_SAI=$SAI_SAI\nexport SAI_SIN=$SAI_SIN\nexport SAI_SKR=$SAI_SKR\nexport SAI_DAD=$SAI_DAD\nexport SAI_MOM=$SAI_MOM\nexport SAI_VOX=$SAI_VOX\nexport SAI_TUB=$SAI_TUB\nexport SAI_TAP=$SAI_TAP\nexport SAI_TOP=$SAI_TOP\nEOF\n\ncat > addresses.json << EOF\n{\n    \"SAI_GEM\": \"$SAI_GEM\",\n    \"SAI_GOV\": \"$SAI_GOV\",\n    \"SAI_PIP\": \"$SAI_PIP\",\n    \"SAI_PEP\": \"$SAI_PEP\",\n    \"SAI_PIT\": \"$SAI_PIT\",\n    \"SAI_ADM\": \"$SAI_ADM\",\n    \"SAI_SAI\": \"$SAI_SAI\",\n    \"SAI_SIN\": \"$SAI_SIN\",\n    \"SAI_SKR\": \"$SAI_SKR\",\n    \"SAI_DAD\": \"$SAI_DAD\",\n    \"SAI_MOM\": \"$SAI_MOM\",\n    \"SAI_VOX\": \"$SAI_VOX\",\n    \"SAI_TUB\": \"$SAI_TUB\",\n    \"SAI_TAP\": \"$SAI_TAP\",\n    \"SAI_TOP\": \"$SAI_TOP\"\n}\nEOF\n"
  },
  {
    "path": "bin/deploy-fab",
    "content": "#!/usr/bin/env bash\nset -ex\n\nexport SOLC_FLAGS=${SOLC_FLAGS:-\"--optimize\"}\nexport ETH_GAS=${ETH_GAS:-\"3500000\"}\nexport ETH_FROM=${ETH_FROM:-$(seth rpc eth_coinbase)}\n\ndapp --use solc:0.4.25 build --extract\n\nexport SETH_ASYNC=yes\n\nETH_NONCE=$(seth nonce \"$ETH_FROM\")\nGEM_FABtx=$(ETH_NONCE=$ETH_NONCE dapp create GemFab)\nVOX_FABtx=$(ETH_NONCE=$((ETH_NONCE + 1)) dapp create VoxFab)\nTUB_FABtx=$(ETH_NONCE=$((ETH_NONCE + 2)) dapp create TubFab)\nTAP_FABtx=$(ETH_NONCE=$((ETH_NONCE + 3)) dapp create TapFab)\nTOP_FABtx=$(ETH_NONCE=$((ETH_NONCE + 4)) dapp create TopFab)\nMOM_FABtx=$(ETH_NONCE=$((ETH_NONCE + 5)) dapp create MomFab)\nDAD_FABtx=$(ETH_NONCE=$((ETH_NONCE + 6)) dapp create DadFab)\n\nexport SETH_ASYNC=no\n\nGEM_FAB=$(seth receipt \"$GEM_FABtx\" contractAddress)\nVOX_FAB=$(seth receipt \"$VOX_FABtx\" contractAddress)\nTUB_FAB=$(seth receipt \"$TUB_FABtx\" contractAddress)\nTAP_FAB=$(seth receipt \"$TAP_FABtx\" contractAddress)\nTOP_FAB=$(seth receipt \"$TOP_FABtx\" contractAddress)\nMOM_FAB=$(seth receipt \"$MOM_FABtx\" contractAddress)\nDAD_FAB=$(seth receipt \"$DAD_FABtx\" contractAddress)\n\ncat > \"load-fab-$(seth chain)\" << EOF\n#!/bin/bash\n\n# fab deployment on $(seth chain) from $(git rev-parse HEAD)\n# $(date)\n\nexport GEM_FAB=$GEM_FAB\nexport VOX_FAB=$VOX_FAB\nexport TAP_FAB=$TAP_FAB\nexport TUB_FAB=$TUB_FAB\nexport TOP_FAB=$TOP_FAB\nexport MOM_FAB=$MOM_FAB\nexport DAD_FAB=$DAD_FAB\nEOF\n"
  },
  {
    "path": "bin/deploy-kovan",
    "content": "#!/usr/bin/env bash\n\nexport SAI_GEM=0xd0a1e359811322d97991e03f863a0c30c2cf029c\nexport SAI_GOV=0xaaf64bfcc32d0f15873a02163e7e500671a4ffcd\nexport SAI_PIP=0xa944bd4b25c9f186a846fd5668941aa3d3b8425f\nexport SAI_PEP=0x02998f73fabb52282664094b0ff87741a1ce9030\nexport SAI_PIT=0xbd747742b0f1f9791d3e6b85f8797a0cf4fbf10b\n\nbin/deploy-fab\n. load-fab-kovan\nbin/deploy\n"
  },
  {
    "path": "bin/deploy-pre",
    "content": "#!/usr/bin/env bash\nset -ex\n\nexport SOLC_FLAGS=${SOLC_FLAGS:-\"--optimize\"}\nexport ETH_GAS=${ETH_GAS:-\"3500000\"}\nexport ETH_FROM=${ETH_FROM:-$(seth rpc eth_coinbase)}\n\ndapp --use solc:0.4.25 build --extract\n\n# ETHUSD feed\nexport SAI_PIP='0x729D19f657BD0614b4985Cf1D82531c67569197B'\n\n# MKRUSD feed\nexport SAI_PEP='0x99041F808D598B782D5a3e498681C2452A31da08'\n\n# WETH9\nexport SAI_GEM='0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'\n\n# Token burner\nSAI_PIT=$(dapp create GemPit)\nexport SAI_PIT\n\n# MKR address\nexport SAI_GOV='0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2'\n\n# Chief\n## Voting IOU\nSAI_IOU=$(dapp create DSToken \"$(seth --to-bytes32 \"$(seth --from-ascii 'IOU')\")\")\nSAI_ADM=$(dapp create DSChief \"$SAI_GOV\" \"$SAI_IOU\" 5)\nexport SAI_IOU\nexport SAI_ADM\nseth send \"$SAI_IOU\" 'setOwner(address)' \"$SAI_ADM\"\n\ncat > \"load-pre-$(seth chain)\" << EOF\ntest -z $SAI_GEM && GEMtx=$(dapp create DSToken \"$(seth --to-bytes32 \"$(seth --from-ascii 'ETH')\")\")\n#!/bin/bash\n\n# pre-sai deployment on $(seth chain) from $(git rev-parse HEAD)\n# $(date)\n\nexport SAI_GEM=$SAI_GEM\nexport SAI_GOV=$SAI_GOV\nexport SAI_PIP=$SAI_PIP\nexport SAI_PEP=$SAI_PEP\nexport SAI_PIT=$SAI_PIT\nexport SAI_ADM=$SAI_ADM\nexport SAI_IOU=$SAI_IOU\nEOF\n"
  },
  {
    "path": "bin/sai",
    "content": "#!/usr/bin/env bash\nset -e\nPATH=${0%/*/*}/libexec/sai:$PATH sai \"$@\"\n"
  },
  {
    "path": "libexec/sai/sai",
    "content": "#!/usr/bin/env bash\n### sai -- command-line Ethereum RPC client\n### Usage: sai [<options>] <command> [<args>]\n###    or: sai <command> --help\n###\n### Sai is a simple version of the diversely collateralized Dai stablecoin.\n###\n### In this model there is one type of underlying collateral (called gems).\n### The SKR token represents claims on the system's excess gems, and is the\n### only admissible type of collateral.  Gems can be converted to/from SKR.\n###\n### Any transfers of sai or SKR are done using the normal ERC20 interface;\n### until settlement mode is triggered, sai users should only need ERC20.\n###\n### To conveniently perform ERC20 transfers, see the token(1) program\n### available at <https://github.com/dapphub/token>.\n###\n### Sai options:\n###\n###    -C, --cup=<id>             ID of cup to perform operation on\n###        --tub=<address>        address of Tub to perform operation on\n###        --tap=<address>        address of Tap to perform operation on\n###        --top=<address>        address of Top to perform operation on\n###\n### Transaction options:\n###\n###    -F, --from=<account>       account from which to send transaction\n###    -G, --gas=<number>         amount of gas to provide with transaction\n\nOPTS=\"sai [<options>] <command> [<args>]\nsai <command> --help\n--\n  Options\nC,cup=id             ID of cup to perform operation on\ntub=address          address of Tub to perform operation on\ntap=address          address of Tap to perform operation on\ntop=address          address of Top to perform operation on\nF,from=address       account from which to send transaction\nG,gas=number         amount of gas to provide with transaction\nh                    display output in human-readable form\n\"\n\nset -e\n\nif [[ $2 = --help ]]; then\n  exec \"${0##*/}\" help -- \"$1\"\nelif [[ $2 = --usage ]]; then\n  \"${0##*/}\" help -- \"$1\"\n  exit 1\nelif [[ $3 = --usage ]]; then\n  \"${0##*/}\" help -- \"$1-$2\"\n  exit 1\nelif [[ $1 = -* ]] && which \"${0##*/}-$1\" &>/dev/null; then\n  exec \"${0##*/}-$1\" \"${@:2}\"\nfi\n\neval \"$(git rev-parse --parseopt -- \"$@\" <<<\"$OPTS\" || echo exit $?)\"\n\nwhile [[ $1 ]]; do\n  case $1 in\n    --)              shift; break;;\n\n    -C|--cup)        shift; export SAI_CUP=\"$(seth --to-hexdata \"$(seth --to-uint256 \"$1\")\")\";;\n       --tub)        shift; export SAI_TUB=$1;;\n       --tap)        shift; export SAI_TAP=$1;;\n       --top)        shift; export SAI_TOP=$1;;\n\n    -F|--from)       shift; export ETH_FROM=$1;;\n    -G|--gas)        shift; export ETH_GAS=$1;;\n    \n    -h)                     export SAI_HUMAN=1;;\n\n    *) printf \"${0##*/}: internal error: %q\\n\" \"$1\"; exit 1\n  esac; shift\ndone\n\nexport SAI_TUB=${SAI_TUB:-@sai_tub}\nexport SAI_TAP=${SAI_TAP:-@sai_tap}\nexport SAI_TOP=${SAI_TOP:-@sai_top}\n\n\"${0##*/}-${1-help}\" \"${@:2}\"\n"
  },
  {
    "path": "libexec/sai/sai---help",
    "content": "#!/usr/bin/env bash\nset -e\nsai help\n"
  },
  {
    "path": "libexec/sai/sai-air",
    "content": "#!/usr/bin/env bash\n### sai-air -- get the amount of backing collateral\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"air()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-axe",
    "content": "#!/usr/bin/env bash\n### sai-axe -- get the liquidation penalty\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"axe()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-bite",
    "content": "#!/usr/bin/env bash\n### sai-bite -- initiate liquidation of an undercollateral cup\n### Usage: sai --cup=<id> bite\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai bite --usage\necho >&2 \"Attempting to bite cup id $((${SAI_CUP?}))...\"\nsafe=$(sai safe)\n[[ $safe = true ]] && { echo >&2 \"${0##*/}: error: cup not unsafe\"; exit 1; }\n(set -x; seth send \"${SAI_TUB?}\" \"bite(bytes32)\" \"$SAI_CUP\")\n"
  },
  {
    "path": "libexec/sai/sai-boom",
    "content": "#!/usr/bin/env bash\n### sai-boom -- buy some amount of sai to process joy (surplus)\n### Usage: sai boom <amount-in-skr>\nset -e\n[ $# = 1 ] || sai boom --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Buying $wad SKR-worth amount of SAI from the tub in order to process joy...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TAP?}\" \"boom(uint256)\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-bust",
    "content": "#!/usr/bin/env bash\n### sai-bust -- sell some amount of sai to process woe (bad debt)\n### Usage: sai bust <amount-in-skr>\nset -e\n[ $# = 1 ] || sai bust --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Selling $wad SKR-worth amount of SAI to the tub in order to process woe...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TAP?}\" \"bust(uint256)\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-cage",
    "content": "#!/usr/bin/env bash\n### sai-cage -- lock the system and initiate settlement\n### Usage: sai cage [<final-price>]\n###   if <final-price> is not specified, the last value from the feed will be used\nset -e\nif [ $# = 0 ]\nthen\n  echo >&2 \"Caging the tub, using the final price from the feed\"\n  (set -x; seth send \"${SAI_TOP?}\" \"cage()\")\nelif [ $# = 1 ]\nthen\n  wad=$(sai wad -h \"$1\")\n  echo >&2 \"Caging the tub, final price $wad\"\n  wad=$(sai wad \"$1\")\n  (set -x; seth send \"${SAI_TOP?}\" \"cage(uint256)\" \"$wad\")\nelse\n  sai cage --usage\nfi\n"
  },
  {
    "path": "libexec/sai/sai-caged",
    "content": "#!/usr/bin/env bash\n### sai-caged -- get time of cage event (= 0 if system is not caged)\nset -e\necho \"$(seth --to-dec $(seth call \"${SAI_TOP?}\" 'caged()'))\"\n"
  },
  {
    "path": "libexec/sai/sai-cap",
    "content": "#!/usr/bin/env bash\n### sai-cap -- get the debt ceiling\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"cap()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-cash",
    "content": "#!/usr/bin/env bash\n### sai-cash -- cash in sai balance for gems after cage\nset -e\njam=$(token balance \"$(sai sai)\" \"${ETH_FROM?}\")\necho >&2 \"Cashing in $jam SAI...\"\nwad=$(sai wad $jam)\n(set -x; seth send \"${SAI_TAP?}\" \"cash(uint256)\" $wad )\n"
  },
  {
    "path": "libexec/sai/sai-chi",
    "content": "#!/usr/bin/env bash\n### sai-chi -- get the internal debt price\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"chi()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-cup",
    "content": "#!/usr/bin/env bash\n### sai-cup -- show the cup info\n### Usage: sai --cup=<id> cup\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai cup --usage\necho >&2 \"cup id $((${SAI_CUP?}))...\"\necho \"lad: $(sai lad)\"\necho \"ink: $(sai ink)\"\necho \"tab: $(sai tab)\"\necho \"rap: $(sai rap)\"\n"
  },
  {
    "path": "libexec/sai/sai-cupi",
    "content": "#!/usr/bin/env bash\n### sai-cupi -- get the last cup id\nset -e\nid=$(seth call \"${SAI_TUB?}\" \"cupi()\")\nseth --abi-decode 'f()(uint256)' \"$id\" | seth --to-dec\n"
  },
  {
    "path": "libexec/sai/sai-cups",
    "content": "#!/usr/bin/env bash\n### sai-cups -- list cups created by you\nset -e\necho >&2 \"Cups created by you...\"\nseth rpc eth_getLogs -- -n {} -s \"${SAI_TUB?}\" -i address \\\n                                 -s earliest    -i fromBlock \\\n                                   -n [] -s \"$(seth keccak \"$(seth --from-ascii 'LogNewCup(address,bytes32)')\")\" -i append \\\n                                         -s \"0x$(seth --to-uint256 \"${ETH_FROM?}\")\" -i append \\\n                                   -i topics \\\n                           -i append \\\n  | echo \"[$(paste -sd , -)]\" `# --jsonrpc output is dejsoned :/ ` \\\n  | jshon -a -e data \\\n  | seth --to-dec\n"
  },
  {
    "path": "libexec/sai/sai-din",
    "content": "#!/usr/bin/env bash\n### sai-din -- get the debt backed by CDPs\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"din()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-draw",
    "content": "#!/usr/bin/env bash\n### sai-draw -- issue the specified amount of sai stablecoins\n### Usage: sai --cup=<id> draw <amount-in-sai>\nset -e\n[ $# = 1 ] || sai draw --usage\n[ ! -z \"$SAI_CUP\" ] || sai draw --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Drawing $wad SAI from cup $((${SAI_CUP?}))...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TUB?}\" \"draw(bytes32,uint256)\" \"$SAI_CUP\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-drip",
    "content": "#!/usr/bin/env bash\n### sai-drip -- recalculate the internal debt price\nset -e\n(set -x; seth send \"${SAI_TUB?}\" \"drip()\")\n"
  },
  {
    "path": "libexec/sai/sai-exit",
    "content": "#!/usr/bin/env bash\n### sai-exit -- sell SKR for gems\n### Usage: sai exit <amount-in-skr>\nset -e\n[ $# = 1 ] || sai exit --usage\nink=$(sai wad -h \"$1\")\necho >&2 \"Sending $ink SKR to TUB...\"\nink=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TUB?}\" \"exit(uint256)\" \"$ink\")\n"
  },
  {
    "path": "libexec/sai/sai-fee",
    "content": "#!/usr/bin/env bash\n### sai-fee -- get the governance fee\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"fee()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-fit",
    "content": "#!/usr/bin/env bash\n### sai-fit -- get the gem per skr settlement price\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"fit()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-fix",
    "content": "#!/usr/bin/env bash\n### sai-fix -- get the gem per sai settlement price\nset -e\nray=$(seth call \"${SAI_TOP?}\" \"fix()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-fog",
    "content": "#!/usr/bin/env bash\n### sai-fog -- get the amount of skr pending liquidation\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"fog()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-free",
    "content": "#!/usr/bin/env bash\n### sai-free -- remove excess SKR collateral from a cup\n### Usage: sai --cup=<id> free <amount-in-skr>\nset -e\n[ $# = 1 ] || sai free --usage\n[ ! -z \"$SAI_CUP\" ] || sai free --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Freeing $wad SKR from cup $((${SAI_CUP?}))...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TUB?}\" \"free(bytes32,uint256)\" \"$SAI_CUP\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-gem",
    "content": "#!/usr/bin/env bash\n### sai-gem -- get the collateral token\nset -e\ngem=$(seth call \"${SAI_TUB?}\" 'gem()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$gem\")\"\n"
  },
  {
    "path": "libexec/sai/sai-give",
    "content": "#!/usr/bin/env bash\n### sai-give -- transfer ownership of a cup\n### Usage: sai --cup=<id> give <address>\nset -e\n[ $# = 1 ] || sai give --usage\n[ ! -z \"$SAI_CUP\" ] || sai give --usage\necho >&2 \"Giving cup $((${SAI_CUP?})) to \\\"${1?}\\\"...\"\n(set -x; seth send \"${SAI_TUB?}\" \"give(bytes32,address)\" \"$SAI_CUP\" \"$1\")\n"
  },
  {
    "path": "libexec/sai/sai-gov",
    "content": "#!/usr/bin/env bash\n### sai-gov -- get the gov token\nset -e\ngov=$(seth call \"${SAI_TUB?}\" 'gov()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$gov\")\"\n"
  },
  {
    "path": "libexec/sai/sai-heal",
    "content": "#!/usr/bin/env bash\n### sai-heal -- cancel debt\nset -e\n(set -x; seth send \"${SAI_TAP?}\" \"heal()\")\n"
  },
  {
    "path": "libexec/sai/sai-help",
    "content": "#!/usr/bin/env bash\n### sai-help -- print help about sai(1) or one of its subcommands\n### Usage: sai help [<command>]\n###    or: sai <command> --help\n\nBUGS=https://github.com/makerdao/sai/issues/new\n\nname=sai\nfile=${0%-*}${1+-$1}\nheader=$(perl -ne 'print \"$2\\n\" if /^(\\S)\\1\\1(?: (.*))?/' \"$file\")\n\nif ! [[ $header ]]; then\n  sed \"s/^/${0##*/}: /\" \"$file\"\nelif [[ $(wc -l <<<\"$header\") = 1 ]]; then\n  echo \"$header\"\nelse\n  sed \"1{/^$name\\\\S* -- /d;}\" <<<\"$header\"\nfi\n\n[[ $1 ]] && exit\n\nfor file in ${0%/*}/$name-*; do\n  basename=${file##*/}\n  if [[ -L $file ]]; then\n    continue\n  elif [[ ${#basename} = 7 ]] || [[ ${#basename} = 11 ]]; then\n    special_commands+=(\"$file\")\n  else\n    normal_commands+=(\"$file\")\n  fi\ndone\n\nlist-commands() {\n  cat \"$@\" |\n  perl -ne 'print \"$2 $3\\n\" if /^(\\S)\\1\\1 '\"$name\"'-(\\S+) -- (.*)/' |\n  while read -r name label; do\n    printf \"   %-14s  %s\\n\" \"${name/-/ }\" \"$label\"\n  done | LANG=C sort\n}\n\ncat <<.\n\nSpecial commands:\n\n$(list-commands \"${special_commands[@]}\")\n\nCommands:\n\n$(list-commands \"${normal_commands[@]}\")\n\nReport bugs to <$BUGS>.\n.\n"
  },
  {
    "path": "libexec/sai/sai-ink",
    "content": "#!/usr/bin/env bash\n### sai-ink -- get the amount of skr collateral locked in a cup\n### Usage: sai --cup=<id> ink\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai ink --usage\nwad=$(seth call \"${SAI_TUB?}\" \"ink(bytes32)\" \"${SAI_CUP?}\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-join",
    "content": "#!/usr/bin/env bash\n### sai-join -- buy SKR for gems\n### Usage: sai join <amount-in-skr>\nset -e\n[ $# = 1 ] || sai join --usage\njam=$(sai wad -h \"$1\")\necho >&2 \"Generating $jam SKR depositing GEM...\"\njam=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TUB?}\" \"join(uint256)\" \"$jam\")\n"
  },
  {
    "path": "libexec/sai/sai-joy",
    "content": "#!/usr/bin/env bash\n### sai-joy -- get the amount of surplus sai\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"joy()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-lad",
    "content": "#!/usr/bin/env bash\n### sai-lad -- get the owner of a cup\n### Usage: sai --cup=<id> lad\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai lad --usage\nlad=$(seth call \"${SAI_TUB?}\" 'lad(bytes32)' \"${SAI_CUP?}\")\necho \"0x$(seth --abi-decode 'f()(address)' \"$lad\")\"\n"
  },
  {
    "path": "libexec/sai/sai-lock",
    "content": "#!/usr/bin/env bash\n### sai-lock -- post additional SKR collateral to a cup\n### Usage: sai --cup=<id> lock <amount-in-skr>\nset -e\n[ $# = 1 ] || sai lock --usage\n[ ! -z \"$SAI_CUP\" ] || sai lock --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Locking $wad SKR in cup $((${SAI_CUP?}))...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TUB?}\" \"lock(bytes32,uint256)\" \"$SAI_CUP\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-mat",
    "content": "#!/usr/bin/env bash\n### sai-mat -- get the liquidation ratio\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"mat()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-off",
    "content": "#!/usr/bin/env bash\n### sai-off -- get the cage flag\nset -e\nseth call \"${SAI_TUB?}\" \"off()(bool)\"\n"
  },
  {
    "path": "libexec/sai/sai-open",
    "content": "#!/usr/bin/env bash\n### sai-open -- create a new cup (collateralized debt position)\nset -e\necho >&2 \"Opening cup...\"\nexport SETH_ASYNC=yes\ntx=$(set -x; seth send \"${SAI_TUB?}\" \"open()(bytes32)\")\nexport SETH_ASYNC=no\necho >&2 -n \"Waiting for transaction receipt...\"\nnumber=$(SETH_TICK=true seth receipt \"$tx\" blockNumber)\necho >&2\nseth rpc eth_getLogs -- -n {} -s \"${SAI_TUB?}\" -i address \\\n                                 -s \"$number\"  -i fromBlock \\\n                                 -s \"$number\"  -i toBlock \\\n                                   -n [] -s \"$(seth keccak \"$(seth --from-ascii 'LogNewCup(address,bytes32)')\")\" -i append \\\n                                         -s \"0x$(seth --to-uint256 \"${ETH_FROM?}\")\" -i append \\\n                                   -i topics \\\n                           -i append \\\n  | echo \"[$(paste -sd , -)]\" `# --jsonrpc output is dejsoned :/ ` \\\n  | jshon -a -e data -u -p -e transactionHash -u \\\n  | grep -B 1 \"$tx\" \\\n  | head -1 \\\n  | seth --to-dec \\\n  | { read -r id; echo \"Opened cup $id\"; }\n"
  },
  {
    "path": "libexec/sai/sai-out",
    "content": "#!/usr/bin/env bash\n### sai-out -- get the post cage exit flag\nset -e\nseth call \"${SAI_TUB?}\" \"out()(bool)\"\n"
  },
  {
    "path": "libexec/sai/sai-par",
    "content": "#!/usr/bin/env bash\n### sai-par -- get the accrued holder fee (ref per sai)\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\nvox_address=\"0x$(seth --abi-decode 'f()(address)' \"$vox\")\"\nray=$(seth call \"$vox_address\" \"par()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-pep",
    "content": "#!/usr/bin/env bash\n### sai-pep -- get the gov price feed\nset -e\npep=$(seth call \"${SAI_TUB?}\" 'pep()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$pep\")\"\n"
  },
  {
    "path": "libexec/sai/sai-per",
    "content": "#!/usr/bin/env bash\n### sai-per -- get the current entry price (gem per skr)\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"per()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-pie",
    "content": "#!/usr/bin/env bash\n### sai-pie -- get the amount of raw collateral\nset -e\nwad=$(seth call \"${SAI_TUB?}\" \"pie()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-pip",
    "content": "#!/usr/bin/env bash\n### sai-pip -- get the gem price feed\nset -e\npip=$(seth call \"${SAI_TUB?}\" 'pip()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$pip\")\"\n"
  },
  {
    "path": "libexec/sai/sai-pit",
    "content": "#!/usr/bin/env bash\n### sai-pit -- get the liquidator vault\nset -e\npit=$(seth call \"${SAI_TUB?}\" 'pit()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$pit\")\"\n"
  },
  {
    "path": "libexec/sai/sai-prod",
    "content": "#!/usr/bin/env bash\n### sai-prod -- recalculate the accrued holder fee (par)\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\nvox_address=\"0x$(seth --abi-decode 'f()(address)' \"$vox\")\"\n(set -x; seth send \"$vox_address\" \"prod()\")\n"
  },
  {
    "path": "libexec/sai/sai-rap",
    "content": "#!/usr/bin/env bash\n### sai-rap -- get the amount of governance debt\n### Usage: sai --cup=<id> rap\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai rap --usage\nwad=$(seth call \"${SAI_TUB?}\" \"rap(bytes32)\" \"${SAI_CUP?}\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-ray",
    "content": "#!/usr/bin/env node\n/// sai-ray -- parse and display a 27-decimal fixed-point number\nvar BigNumber = require(\"bignumber.js\")\nvar ray = process.argv[2], match\nvar rpad = (x, y, n) => x + repeat(y, n - x.length)\nvar lpad = (x, y, n) => repeat(y, n - x.length) + x\nvar repeat = (x, n) => n > 0 ? new Array(n + 1).join(x) : \"\"\nvar toHex = ray => new BigNumber(ray.replace(\".\", \"\")).toString(16)\n   \nif (match = ray.match(/^(\\d+\\.)(\\d{1,27})$/)) {\n  ray = match[1] + rpad(match[2], \"0\", 27)\n} else if (/^0x[0-9a-f]+/.test(ray)) {\n  ray = lpad(new BigNumber(ray).toString(10), \"0\", 27)\n  ray = ray.replace(/.{27}$/, \".$&\").replace(/^\\./, \"0.\")\n} else {\n  console.error(\"sai---ray: error: number must have decimal point\")\n  process.exit(1)\n}\n\nif (process.env.SAI_HUMAN) {\n  console.log(ray)\n} else {\n  console.log(`0x${lpad(toHex(ray), \"0\", 64)}`)\n}\n"
  },
  {
    "path": "libexec/sai/sai-rhi",
    "content": "#!/usr/bin/env bash\n### sai-rhi -- get the internal debt price including governance fee\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"rhi()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-rho",
    "content": "#!/usr/bin/env bash\n### sai-rho -- get the time of last drip\nset -e\ntime=$(seth call \"${SAI_TUB?}\" \"rho()\")\ntime_unix=$(seth --to-dec \"$time\")\necho \"$time_unix\"\n"
  },
  {
    "path": "libexec/sai/sai-s2s",
    "content": "#!/usr/bin/env bash\n### sai-s2s -- get the skr per sai rate (for boom and bust)\nset -e\nray=$(seth call \"${SAI_TAP?}\" \"s2s()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-safe",
    "content": "#!/usr/bin/env bash\n### sai-safe -- determine if a cup is safe\n### Usage: sai --cup=<id> safe\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai safe --usage\nsafe=$(seth call \"${SAI_TUB?}\" 'safe(bytes32)' \"${SAI_CUP?}\")\nseth --abi-decode 'f(bytes32)(bool)' \"$safe\"\n"
  },
  {
    "path": "libexec/sai/sai-sai",
    "content": "#!/usr/bin/env bash\n### sai-sai -- get the sai token\nset -e\nsai=$(seth call \"${SAI_TUB?}\" 'sai()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$sai\")\"\n"
  },
  {
    "path": "libexec/sai/sai-setAxe",
    "content": "#!/usr/bin/env bash\n### sai-setAxe -- update the liquidation penalty\n### Usage: sai setAxe <new-axe>\nset -e\n[ $# = 1 ] || sai setAxe --usage\nray=$(sai ray -h \"$1\")\necho >&2 \"Setting axe to $ray...\"\nray=$(sai ray \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setAxe(uint256)\" \"$ray\")\n"
  },
  {
    "path": "libexec/sai/sai-setCap",
    "content": "#!/usr/bin/env bash\n### sai-setCap -- update the debt ceiling\n### Usage: sai setCap <new-cap>\nset -e\n[ $# = 1 ] || sai setCap --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Setting cap to $wad...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setCap(uint256)\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-setFee",
    "content": "#!/usr/bin/env bash\n### sai-setFee -- update the stability fee\n### Usage: sai setFee <new-fee>\nset -e\n[ $# = 1 ] || sai setFee --usage\nray=$(sai ray -h \"$1\")\necho >&2 \"Setting fee to $ray...\"\nray=$(sai ray \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setFee(uint256)\" \"$ray\")\n"
  },
  {
    "path": "libexec/sai/sai-setMat",
    "content": "#!/usr/bin/env bash\n### sai-setMat -- update the liquidation ratio\n### Usage: sai setMat <new-mat>\nset -e\n[ $# = 1 ] || sai setMat --usage\nray=$(sai ray -h \"$1\")\necho >&2 \"Setting mat to $ray...\"\nray=$(sai ray \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setMat(uint256)\" \"$ray\")\n"
  },
  {
    "path": "libexec/sai/sai-setTapGap",
    "content": "#!/usr/bin/env bash\n### sai-setTapGap -- update the spread on `boom` and `bust`\n### Usage: sai tapGap <new-gap>\nset -e\n[ $# = 1 ] || sai tap tapGap --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Setting gap to $wad...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setTapGap(uint256)\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-setTax",
    "content": "#!/usr/bin/env bash\n### sai-setTax -- update the stability fee\n### Usage: sai setTax <new-tax>\nset -e\n[ $# = 1 ] || sai setTax --usage\nray=$(sai ray -h \"$1\")\necho >&2 \"Setting tax to $ray...\"\nray=$(sai ray \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setTax(uint256)\" \"$ray\")\n"
  },
  {
    "path": "libexec/sai/sai-setTubGap",
    "content": "#!/usr/bin/env bash\n### sai-setTubGap -- update the spread on `join` and `exit`\n### Usage: sai setTubGap <new-gap>\nset -e\n[ $# = 1 ] || sai setTubGap --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Setting tubGap to $wad...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_MOM?}\" \"setTubGap(uint256)\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-setWay",
    "content": "#!/usr/bin/env bash\n### sai-setWay -- update the holder fee (interest rate)\n### Usage: sai setWay <new-way>\nset -e\n[ $# = 1 ] || sai setWay --usage\nray=$(sai ray -h \"$1\")\necho >&2 \"Setting way to $ray...\"\nray=$(sai ray \"$1\")\n(set -x; seth send \"${SAI_MOM}\" \"setWay(uint256)\" \"$ray\")\n"
  },
  {
    "path": "libexec/sai/sai-shut",
    "content": "#!/usr/bin/env bash\n### sai-shut -- close a cup\n### Usage: sai --cup=<id> shut\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai shut --usage\necho >&2 \"Closing cup $((${SAI_CUP?}))...\"\n(set -x; seth send \"${SAI_TUB?}\" \"shut(bytes32)\" \"$SAI_CUP\")\n"
  },
  {
    "path": "libexec/sai/sai-sin",
    "content": "#!/usr/bin/env bash\n### sai-sin -- get the sin token\nset -e\nsin=$(seth call \"${SAI_TUB?}\" 'sin()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$sin\")\"\n"
  },
  {
    "path": "libexec/sai/sai-skr",
    "content": "#!/usr/bin/env bash\n### sai-skr -- get the skr token\nset -e\nskr=$(seth call \"${SAI_TUB?}\" 'skr()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$skr\")\"\n"
  },
  {
    "path": "libexec/sai/sai-tab",
    "content": "#!/usr/bin/env bash\n### sai-tab -- get the amount of debt in a cup\n### Usage: sai --cup=<id> tab\nset -e\n[ ! -z \"$SAI_CUP\" ] || sai tab --usage\nwad=$(seth call \"${SAI_TUB?}\" \"tab(bytes32)\" \"${SAI_CUP?}\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-tag",
    "content": "#!/usr/bin/env bash\n### sai-tag -- get the reference price (ref per skr)\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"tag()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-tapAsk",
    "content": "#!/usr/bin/env bash\n### sai-tapAsk -- get the amount of skr in sai for bust\nset -e\n[ $# = 1 ] || sai tapAsk --usage\nwad=$(seth call \"${SAI_TAP?}\" \"ask(uint256)\" $(sai wad \"$1\"))\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-tapBid",
    "content": "#!/usr/bin/env bash\n### sai-tapBid -- get the amount of skr in sai for boom\nset -e\n[ $# = 1 ] || sai tapBid --usage\nwad=$(seth call \"${SAI_TAP?}\" \"bid(uint256)\" $(sai wad \"$1\"))\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-tapGap",
    "content": "#!/usr/bin/env bash\n### sai-tapGap -- get the spread on `boom` and `bust`\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"gap()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-tau",
    "content": "#!/usr/bin/env bash\n### sai-tau -- get the time of last prod\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\nvox_address=\"0x$(seth --abi-decode 'f()(address)' \"$vox\")\"\ntime=$(seth call \"$vox_address\" \"tau()\")\ntime_unix=$(seth --to-dec \"$time\")\necho \"$time_unix\"\n"
  },
  {
    "path": "libexec/sai/sai-tax",
    "content": "#!/usr/bin/env bash\n### sai-tax -- get the stability fee\nset -e\nray=$(seth call \"${SAI_TUB?}\" \"tax()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-tubAsk",
    "content": "#!/usr/bin/env bash\n### sai-tubAsk -- get the amount of skr in gem for join\nset -e\n[ $# = 1 ] || sai tubAsk --usage\nwad=$(seth call \"${SAI_TUB?}\" \"ask(uint256)\" $(sai wad \"$1\"))\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-tubBid",
    "content": "#!/usr/bin/env bash\n### sai-tubBid -- get the amount of skr in gem for exit\nset -e\n[ $# = 1 ] || sai tubBid --usage\nwad=$(seth call \"${SAI_TUB?}\" \"bid(uint256)\" $(sai wad \"$1\"))\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-tubGap",
    "content": "#!/usr/bin/env bash\n### sai-tubGap -- get the spread on `join` and `exit`\nset -e\nwad=$(seth call \"$SAI_TUB\" \"gap()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "libexec/sai/sai-vent",
    "content": "#!/usr/bin/env bash\n### sai-vent -- process a caged tub\nset -e\n(set -x; seth send \"${SAI_TAP?}\" \"vent()\")\n"
  },
  {
    "path": "libexec/sai/sai-vox",
    "content": "#!/usr/bin/env bash\n### sai-vox -- get the target price engine\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\necho \"0x$(seth --abi-decode 'f()(address)' \"$vox\")\"\n"
  },
  {
    "path": "libexec/sai/sai-wad",
    "content": "#!/usr/bin/env node\n/// sai-wad -- parse and display a 18-decimal fixed-point number\nvar BigNumber = require(\"bignumber.js\")\nvar wad = process.argv[2], match\nvar rpad = (x, y, n) => x + repeat(y, n - x.length)\nvar lpad = (x, y, n) => repeat(y, n - x.length) + x\nvar repeat = (x, n) => n > 0 ? new Array(n + 1).join(x) : \"\"\nvar toHex = wad => new BigNumber(wad.replace(\".\", \"\")).toString(16)\n   \nif (match = wad.match(/^(\\d+\\.)(\\d{1,18})$/)) {\n  wad = match[1] + rpad(match[2], \"0\", 18)\n} else if (/^0x[0-9a-f]+/.test(wad)) {\n  wad = lpad(new BigNumber(wad).toString(10), \"0\", 18)\n  wad = wad.replace(/.{18}$/, \".$&\").replace(/^\\./, \"0.\")\n} else {\n  console.error(\"sai---wad: error: number must have decimal point\")\n  process.exit(1)\n}\n\nif (process.env.SAI_HUMAN) {\n  console.log(wad)\n} else {\n  console.log(`0x${lpad(toHex(wad), \"0\", 64)}`)\n}\n"
  },
  {
    "path": "libexec/sai/sai-way",
    "content": "#!/usr/bin/env bash\n### sai-way -- get the holder fee (interest rate)\nset -e\nvox=$(seth call \"${SAI_TUB?}\" 'vox()')\nvox_address=\"0x$(seth --abi-decode 'f()(address)' \"$vox\")\"\nray=$(seth call \"$vox_address\" \"way()\")\nsai ray -h \"$ray\"\n"
  },
  {
    "path": "libexec/sai/sai-wipe",
    "content": "#!/usr/bin/env bash\n### sai-wipe -- repay some portion of your existing sai debt\n### Usage: sai --cup=<id> wipe <amount-in-sai>\nset -e\n[ $# = 1 ] || sai wipe --usage\n[ ! -z \"$SAI_CUP\" ] || sai wipe --usage\nwad=$(sai wad -h \"$1\")\necho >&2 \"Wiping $wad SAI from cup $((${SAI_CUP?}))...\"\nwad=$(sai wad \"$1\")\n(set -x; seth send \"${SAI_TUB?}\" \"wipe(bytes32,uint256)\" \"$SAI_CUP\" \"$wad\")\n"
  },
  {
    "path": "libexec/sai/sai-woe",
    "content": "#!/usr/bin/env bash\n### sai-woe -- get the amount of bad debt\nset -e\nwad=$(seth call \"${SAI_TAP?}\" \"woe()\")\nsai wad -h \"$wad\"\n"
  },
  {
    "path": "src/fab.sol",
    "content": "pragma solidity ^0.4.18;\n\nimport \"ds-auth/auth.sol\";\nimport 'ds-token/token.sol';\nimport 'ds-guard/guard.sol';\nimport 'ds-roles/roles.sol';\nimport 'ds-value/value.sol';\n\nimport './mom.sol';\n\ncontract GemFab {\n    function newTok(bytes32 name) public returns (DSToken token) {\n        token = new DSToken(name);\n        token.setOwner(msg.sender);\n    }\n}\n\ncontract VoxFab {\n    function newVox() public returns (SaiVox vox) {\n        vox = new SaiVox(10 ** 27);\n        vox.setOwner(msg.sender);\n    }\n}\n\ncontract TubFab {\n    function newTub(DSToken sai, DSToken sin, DSToken skr, ERC20 gem, DSToken gov, DSValue pip, DSValue pep, SaiVox vox, address pit) public returns (SaiTub tub) {\n        tub = new SaiTub(sai, sin, skr, gem, gov, pip, pep, vox, pit);\n        tub.setOwner(msg.sender);\n    }\n}\n\ncontract TapFab {\n    function newTap(SaiTub tub) public returns (SaiTap tap) {\n        tap = new SaiTap(tub);\n        tap.setOwner(msg.sender);\n    }\n}\n\ncontract TopFab {\n    function newTop(SaiTub tub, SaiTap tap) public returns (SaiTop top) {\n        top = new SaiTop(tub, tap);\n        top.setOwner(msg.sender);\n    }\n}\n\ncontract MomFab {\n    function newMom(SaiTub tub, SaiTap tap, SaiVox vox) public returns (SaiMom mom) {\n        mom = new SaiMom(tub, tap, vox);\n        mom.setOwner(msg.sender);\n    }\n}\n\ncontract DadFab {\n    function newDad() public returns (DSGuard dad) {\n        dad = new DSGuard();\n        dad.setOwner(msg.sender);\n    }\n}\n\ncontract DaiFab is DSAuth {\n    GemFab public gemFab;\n    VoxFab public voxFab;\n    TapFab public tapFab;\n    TubFab public tubFab;\n    TopFab public topFab;\n    MomFab public momFab;\n    DadFab public dadFab;\n\n    DSToken public sai;\n    DSToken public sin;\n    DSToken public skr;\n\n    SaiVox public vox;\n    SaiTub public tub;\n    SaiTap public tap;\n    SaiTop public top;\n\n    SaiMom public mom;\n    DSGuard public dad;\n\n    uint8 public step = 0;\n\n    function DaiFab(GemFab gemFab_, VoxFab voxFab_, TubFab tubFab_, TapFab tapFab_, TopFab topFab_, MomFab momFab_, DadFab dadFab_) public {\n        gemFab = gemFab_;\n        voxFab = voxFab_;\n        tubFab = tubFab_;\n        tapFab = tapFab_;\n        topFab = topFab_;\n        momFab = momFab_;\n        dadFab = dadFab_;\n    }\n\n    function makeTokens() public auth {\n        require(step == 0);\n        sai = gemFab.newTok('DAI');\n        sin = gemFab.newTok('SIN');\n        skr = gemFab.newTok('PETH');\n        sai.setName('Dai Stablecoin v1.0');\n        sin.setName('SIN');\n        skr.setName('Pooled Ether');\n        step += 1;\n    }\n\n    function makeVoxTub(ERC20 gem, DSToken gov, DSValue pip, DSValue pep, address pit) public auth {\n        require(step == 1);\n        require(address(gem) != 0x0);\n        require(address(gov) != 0x0);\n        require(address(pip) != 0x0);\n        require(address(pep) != 0x0);\n        require(pit != 0x0);\n        vox = voxFab.newVox();\n        tub = tubFab.newTub(sai, sin, skr, gem, gov, pip, pep, vox, pit);\n        step += 1;\n    }\n\n    function makeTapTop() public auth {\n        require(step == 2);\n        tap = tapFab.newTap(tub);\n        tub.turn(tap);\n        top = topFab.newTop(tub, tap);\n        step += 1;\n    }\n\n    function S(string s) internal pure returns (bytes4) {\n        return bytes4(keccak256(s));\n    }\n\n    function ray(uint256 wad) internal pure returns (uint256) {\n        return wad * 10 ** 9;\n    }\n\n    // Liquidation Ratio   150%\n    // Liquidation Penalty 13%\n    // Stability Fee       0.05%\n    // PETH Fee            0%\n    // Boom/Bust Spread   -3%\n    // Join/Exit Spread    0%\n    // Debt Ceiling        0\n    function configParams() public auth {\n        require(step == 3);\n\n        tub.mold(\"cap\", 0);\n        tub.mold(\"mat\", ray(1.5  ether));\n        tub.mold(\"axe\", ray(1.13 ether));\n        tub.mold(\"fee\", 1000000000158153903837946257);  // 0.5% / year\n        tub.mold(\"tax\", ray(1 ether));\n        tub.mold(\"gap\", 1 ether);\n\n        tap.mold(\"gap\", 0.97 ether);\n\n        step += 1;\n    }\n\n    function verifyParams() public auth {\n        require(step == 4);\n\n        require(tub.cap() == 0);\n        require(tub.mat() == 1500000000000000000000000000);\n        require(tub.axe() == 1130000000000000000000000000);\n        require(tub.fee() == 1000000000158153903837946257);\n        require(tub.tax() == 1000000000000000000000000000);\n        require(tub.gap() == 1000000000000000000);\n\n        require(tap.gap() == 970000000000000000);\n\n        require(vox.par() == 1000000000000000000000000000);\n        require(vox.how() == 0);\n\n        step += 1;\n    }\n\n    function configAuth(DSAuthority authority) public auth {\n        require(step == 5);\n        require(address(authority) != 0x0);\n\n        mom = momFab.newMom(tub, tap, vox);\n        dad = dadFab.newDad();\n\n        vox.setAuthority(dad);\n        vox.setOwner(0);\n        tub.setAuthority(dad);\n        tub.setOwner(0);\n        tap.setAuthority(dad);\n        tap.setOwner(0);\n        sai.setAuthority(dad);\n        sai.setOwner(0);\n        sin.setAuthority(dad);\n        sin.setOwner(0);\n        skr.setAuthority(dad);\n        skr.setOwner(0);\n\n        top.setAuthority(authority);\n        top.setOwner(0);\n        mom.setAuthority(authority);\n        mom.setOwner(0);\n\n        dad.permit(top, tub, S(\"cage(uint256,uint256)\"));\n        dad.permit(top, tub, S(\"flow()\"));\n        dad.permit(top, tap, S(\"cage(uint256)\"));\n\n        dad.permit(tub, skr, S('mint(address,uint256)'));\n        dad.permit(tub, skr, S('burn(address,uint256)'));\n\n        dad.permit(tub, sai, S('mint(address,uint256)'));\n        dad.permit(tub, sai, S('burn(address,uint256)'));\n\n        dad.permit(tub, sin, S('mint(address,uint256)'));\n\n        dad.permit(tap, sai, S('mint(address,uint256)'));\n        dad.permit(tap, sai, S('burn(address,uint256)'));\n        dad.permit(tap, sai, S('burn(uint256)'));\n        dad.permit(tap, sin, S('burn(uint256)'));\n\n        dad.permit(tap, skr, S('mint(uint256)'));\n        dad.permit(tap, skr, S('burn(uint256)'));\n        dad.permit(tap, skr, S('burn(address,uint256)'));\n\n        dad.permit(mom, vox, S(\"mold(bytes32,uint256)\"));\n        dad.permit(mom, vox, S(\"tune(uint256)\"));\n        dad.permit(mom, tub, S(\"mold(bytes32,uint256)\"));\n        dad.permit(mom, tap, S(\"mold(bytes32,uint256)\"));\n        dad.permit(mom, tub, S(\"setPip(address)\"));\n        dad.permit(mom, tub, S(\"setPep(address)\"));\n        dad.permit(mom, tub, S(\"setVox(address)\"));\n\n        dad.setOwner(0);\n        step += 1;\n    }\n}\n"
  },
  {
    "path": "src/fab.t.sol",
    "content": "pragma solidity ^0.4.18;\n\nimport \"ds-test/test.sol\";\nimport './fab.sol';\n\ncontract BinTest is DSTest {\n    GemFab gemFab;\n    VoxFab voxFab;\n    TubFab tubFab;\n    TapFab tapFab;\n    TopFab topFab;\n    MomFab momFab;\n    DadFab dadFab;\n\n    DaiFab daiFab;\n\n    DSToken gem;\n    DSToken gov;\n    DSValue pip;\n    DSValue pep;\n    address pit;\n\n    DSRoles authority;\n\n    function setUp() public {\n        gemFab = new GemFab();\n        voxFab = new VoxFab();\n        tubFab = new TubFab();\n        tapFab = new TapFab();\n        topFab = new TopFab();\n        momFab = new MomFab();\n        dadFab = new DadFab();\n\n        uint startGas = msg.gas;\n        daiFab = new DaiFab(gemFab, voxFab, tubFab, tapFab, topFab, momFab, dadFab);\n        uint endGas = msg.gas;\n        log_named_uint('Deploy DaiFab', startGas - endGas);\n\n        gem = new DSToken('GEM');\n        gov = new DSToken('GOV');\n        pip = new DSValue();\n        pep = new DSValue();\n        pit = address(0x123);\n        authority = new DSRoles();\n        authority.setRootUser(this, true);\n    }\n\n    function testMake() public {\n        uint startGas = msg.gas;\n        daiFab.makeTokens();\n        uint endGas = msg.gas;\n        log_named_uint('Make Tokens', startGas - endGas);\n\n        startGas = msg.gas;\n        daiFab.makeVoxTub(gem, gov, pip, pep, pit);\n        endGas = msg.gas;\n        log_named_uint('Make Vox Tub', startGas - endGas);\n\n        startGas = msg.gas;\n        daiFab.makeTapTop();\n        endGas = msg.gas;\n        log_named_uint('Make Tap Top', startGas - endGas);\n\n        startGas = msg.gas;\n        daiFab.configParams();\n        endGas = msg.gas;\n        log_named_uint('Config Params', startGas - endGas);\n\n        startGas = msg.gas;\n        daiFab.verifyParams();\n        endGas = msg.gas;\n        log_named_uint('Verify Params', startGas - endGas);\n\n        startGas = msg.gas;\n        daiFab.configAuth(authority);\n        endGas = msg.gas;\n        log_named_uint('Config Auth', startGas - endGas);\n    }\n\n    function testFailStep() public {\n        daiFab.makeTokens();\n        daiFab.makeTokens();\n    }\n\n    function testFailStep2() public {\n        daiFab.makeTokens();\n        daiFab.makeTapTop();\n    }\n\n    function testFailStep3() public {\n        daiFab.makeTokens();\n        daiFab.makeVoxTub(gem, gov, pip, pep, pit);\n        daiFab.makeTapTop();\n        daiFab.makeVoxTub(gem, gov, pip, pep, pit);\n    }\n\n    function testFailStep4() public {\n        daiFab.makeTokens();\n        daiFab.makeVoxTub(gem, gov, pip, pep, pit);\n        daiFab.makeTapTop();\n        daiFab.configAuth(authority);\n        daiFab.makeTokens();\n    }\n}\n"
  },
  {
    "path": "src/mom.sol",
    "content": "/// mom.sol -- admin manager\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) 2017  Daniel Brockman <daniel@dapphub.com>\n// Copyright (C) 2017  Rain <rainbreak@riseup.net>\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\nimport 'ds-thing/thing.sol';\nimport './tub.sol';\nimport './top.sol';\nimport './tap.sol';\n\ncontract SaiMom is DSThing {\n    SaiTub  public  tub;\n    SaiTap  public  tap;\n    SaiVox  public  vox;\n\n    function SaiMom(SaiTub tub_, SaiTap tap_, SaiVox vox_) public {\n        tub = tub_;\n        tap = tap_;\n        vox = vox_;\n    }\n    // Debt ceiling\n    function setCap(uint wad) public note auth {\n        tub.mold(\"cap\", wad);\n    }\n    // Liquidation ratio\n    function setMat(uint ray) public note auth {\n        tub.mold(\"mat\", ray);\n        var axe = tub.axe();\n        var mat = tub.mat();\n        require(axe >= RAY && axe <= mat);\n    }\n    // Stability fee\n    function setTax(uint ray) public note auth {\n        tub.mold(\"tax\", ray);\n        var tax = tub.tax();\n        require(RAY <= tax);\n        require(tax < 1000001100000000000000000000);  // 10% / day\n    }\n    // Governance fee\n    function setFee(uint ray) public note auth {\n        tub.mold(\"fee\", ray);\n        var fee = tub.fee();\n        require(RAY <= fee);\n        require(fee < 1000001100000000000000000000);  // 10% / day\n    }\n    // Liquidation fee\n    function setAxe(uint ray) public note auth {\n        tub.mold(\"axe\", ray);\n        var axe = tub.axe();\n        var mat = tub.mat();\n        require(axe >= RAY && axe <= mat);\n    }\n    // Join/Exit Spread\n    function setTubGap(uint wad) public note auth {\n        tub.mold(\"gap\", wad);\n    }\n    // ETH/USD Feed\n    function setPip(DSValue pip_) public note auth {\n        tub.setPip(pip_);\n    }\n    // MKR/USD Feed\n    function setPep(DSValue pep_) public note auth {\n        tub.setPep(pep_);\n    }\n    // TRFM\n    function setVox(SaiVox vox_) public note auth {\n        tub.setVox(vox_);\n    }\n    // Boom/Bust Spread\n    function setTapGap(uint wad) public note auth {\n        tap.mold(\"gap\", wad);\n        var gap = tap.gap();\n        require(gap <= 1.05 ether);\n        require(gap >= 0.95 ether);\n    }\n    // Rate of change of target price (per second)\n    function setWay(uint ray) public note auth {\n        require(ray < 1000001100000000000000000000);  // 10% / day\n        require(ray >  999998800000000000000000000);\n        vox.mold(\"way\", ray);\n    }\n    function setHow(uint ray) public note auth {\n        vox.tune(ray);\n    }\n}\n"
  },
  {
    "path": "src/pit.sol",
    "content": "/// pit.sol -- a simple token burner\n\n// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\nimport \"ds-token/token.sol\";\n\ncontract GemPit {\n    function burn(DSToken gem) public {\n        gem.burn(gem.balanceOf(this));\n    }\n}\n"
  },
  {
    "path": "src/sai.t.sol",
    "content": "pragma solidity ^0.4.18;\n\nimport \"ds-test/test.sol\";\n\nimport \"ds-math/math.sol\";\n\nimport 'ds-token/token.sol';\nimport 'ds-roles/roles.sol';\nimport 'ds-value/value.sol';\n\nimport './weth9.sol';\nimport './mom.sol';\nimport './fab.sol';\nimport './pit.sol';\n\ncontract TestWarp is DSNote {\n    uint256  _era;\n\n    function TestWarp() public {\n        _era = now;\n    }\n\n    function era() public view returns (uint256) {\n        return _era == 0 ? now : _era;\n    }\n\n    function warp(uint age) public note {\n        require(_era != 0);\n        _era = age == 0 ? 0 : _era + age;\n    }\n}\n\ncontract DevTub is SaiTub, TestWarp {\n    function DevTub(\n        DSToken  sai_,\n        DSToken  sin_,\n        DSToken  skr_,\n        ERC20    gem_,\n        DSToken  gov_,\n        DSValue  pip_,\n        DSValue  pep_,\n        SaiVox   vox_,\n        address  pit_\n    ) public\n      SaiTub(sai_, sin_, skr_, gem_, gov_, pip_, pep_, vox_, pit_) {}\n}\n\ncontract DevTop is SaiTop, TestWarp {\n    function DevTop(SaiTub tub_, SaiTap tap_) public SaiTop(tub_, tap_) {}\n}\n\ncontract DevVox is SaiVox, TestWarp {\n    function DevVox(uint par_) SaiVox(par_) public {}\n}\n\ncontract DevVoxFab {\n    function newVox() public returns (DevVox vox) {\n        vox = new DevVox(10 ** 27);\n        vox.setOwner(msg.sender);\n    }\n}\n\ncontract DevTubFab {\n    function newTub(DSToken sai, DSToken sin, DSToken skr, DSToken gem, DSToken gov, DSValue pip, DSValue pep, SaiVox vox, address pit) public returns (DevTub tub) {\n        tub = new DevTub(sai, sin, skr, gem, gov, pip, pep, vox, pit);\n        tub.setOwner(msg.sender);\n    }\n}\n\ncontract DevTopFab {\n    function newTop(DevTub tub, SaiTap tap) public returns (DevTop top) {\n        top = new DevTop(tub, tap);\n        top.setOwner(msg.sender);\n    }\n}\n\ncontract DevDadFab {\n    function newDad() public returns (DSGuard dad) {\n        dad = new DSGuard();\n        // convenience in tests\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('mint(uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('burn(uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('mint(address,uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sai(), bytes4(keccak256('burn(address,uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('mint(uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('burn(uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('mint(address,uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).sin(), bytes4(keccak256('burn(address,uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('mint(uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('burn(uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('mint(address,uint256)')));\n        dad.permit(DaiFab(msg.sender).owner(), DaiFab(msg.sender).skr(), bytes4(keccak256('burn(address,uint256)')));\n        dad.setOwner(msg.sender);\n    }\n}\n\ncontract FakePerson {\n    SaiTap  public tap;\n    DSToken public sai;\n\n    function FakePerson(SaiTap _tap) public {\n        tap = _tap;\n        sai = tap.sai();\n        sai.approve(tap);\n    }\n\n    function cash() public {\n        tap.cash(sai.balanceOf(this));\n    }\n}\n\ncontract SaiTestBase is DSTest, DSMath {\n    DevVox   vox;\n    DevTub   tub;\n    DevTop   top;\n    SaiTap   tap;\n\n    SaiMom   mom;\n\n    WETH9    gem;\n    DSToken  sai;\n    DSToken  sin;\n    DSToken  skr;\n    DSToken  gov;\n\n    GemPit   pit;\n\n    DSValue  pip;\n    DSValue  pep;\n    DSRoles  dad;\n\n    function ray(uint256 wad) internal pure returns (uint256) {\n        return wad * 10 ** 9;\n    }\n    function wad(uint256 ray_) internal pure returns (uint256) {\n        return wdiv(ray_, RAY);\n    }\n\n    function mark(uint price) internal {\n        pip.poke(bytes32(price));\n    }\n    function mark(DSToken tkn, uint price) internal {\n        if (address(tkn) == address(gov)) pep.poke(bytes32(price));\n        else if (address(tkn) == address(gem)) mark(price);\n    }\n    function warp(uint256 age) internal {\n        vox.warp(age);\n        tub.warp(age);\n        top.warp(age);\n    }\n\n    function setUp() public {\n        GemFab gemFab = new GemFab();\n        DevVoxFab voxFab = new DevVoxFab();\n        DevTubFab tubFab = new DevTubFab();\n        TapFab tapFab = new TapFab();\n        DevTopFab topFab = new DevTopFab();\n        MomFab momFab = new MomFab();\n        DevDadFab dadFab = new DevDadFab();\n\n        DaiFab daiFab = new DaiFab(gemFab, VoxFab(voxFab), TubFab(tubFab), tapFab, TopFab(topFab), momFab, DadFab(dadFab));\n\n        gem = new WETH9();\n        gem.deposit.value(100 ether)();\n        gov = new DSToken('GOV');\n        pip = new DSValue();\n        pep = new DSValue();\n        pit = new GemPit();\n\n        daiFab.makeTokens();\n        daiFab.makeVoxTub(ERC20(gem), gov, pip, pep, pit);\n        daiFab.makeTapTop();\n        daiFab.configParams();\n        daiFab.verifyParams();\n        DSRoles authority = new DSRoles();\n        authority.setRootUser(this, true);\n        daiFab.configAuth(authority);\n\n        sai = DSToken(daiFab.sai());\n        sin = DSToken(daiFab.sin());\n        skr = DSToken(daiFab.skr());\n        vox = DevVox(daiFab.vox());\n        tub = DevTub(daiFab.tub());\n        tap = SaiTap(daiFab.tap());\n        top = DevTop(daiFab.top());\n        mom = SaiMom(daiFab.mom());\n        dad = DSRoles(daiFab.dad());\n\n        sai.approve(tub);\n        skr.approve(tub);\n        gem.approve(tub, uint(-1));\n        gov.approve(tub);\n\n        sai.approve(tap);\n        skr.approve(tap);\n\n        mark(1 ether);\n        mark(gov, 1 ether);\n\n        mom.setCap(20 ether);\n        mom.setAxe(ray(1 ether));\n        mom.setMat(ray(1 ether));\n        mom.setTax(ray(1 ether));\n        mom.setFee(ray(1 ether));\n        mom.setTubGap(1 ether);\n        mom.setTapGap(1 ether);\n    }\n}\n\ncontract SaiTubTest is SaiTestBase {\n    function testBasic() public {\n        assertEq( skr.balanceOf(tub), 0 ether );\n        assertEq( skr.balanceOf(this), 0 ether );\n        assertEq( gem.balanceOf(tub), 0 ether );\n\n        // edge case\n        assertEq( uint256(tub.per()), ray(1 ether) );\n        tub.join(10 ether);\n        assertEq( uint256(tub.per()), ray(1 ether) );\n\n        assertEq( skr.balanceOf(this), 10 ether );\n        assertEq( gem.balanceOf(tub), 10 ether );\n        // price formula\n        tub.join(10 ether);\n        assertEq( uint256(tub.per()), ray(1 ether) );\n        assertEq( skr.balanceOf(this), 20 ether );\n        assertEq( gem.balanceOf(tub), 20 ether );\n\n        var cup = tub.open();\n\n        assertEq( skr.balanceOf(this), 20 ether );\n        assertEq( skr.balanceOf(tub), 0 ether );\n        tub.lock(cup, 10 ether); // lock skr token\n        assertEq( skr.balanceOf(this), 10 ether );\n        assertEq( skr.balanceOf(tub), 10 ether );\n\n        assertEq( sai.balanceOf(this), 0 ether);\n        tub.draw(cup, 5 ether);\n        assertEq( sai.balanceOf(this), 5 ether);\n\n\n        assertEq( sai.balanceOf(this), 5 ether);\n        tub.wipe(cup, 2 ether);\n        assertEq( sai.balanceOf(this), 3 ether);\n\n        assertEq( sai.balanceOf(this), 3 ether);\n        assertEq( skr.balanceOf(this), 10 ether );\n        tub.shut(cup);\n        assertEq( sai.balanceOf(this), 0 ether);\n        assertEq( skr.balanceOf(this), 20 ether );\n    }\n    function testGive() public {\n        var cup = tub.open();\n        assertEq(tub.lad(cup), this);\n\n        address ali = 0x456;\n        tub.give(cup, ali);\n        assertEq(tub.lad(cup), ali);\n    }\n    function testFailGiveNotLad() public {\n        var cup = tub.open();\n        address ali = 0x456;\n        tub.give(cup, ali);\n\n        address bob = 0x789;\n        tub.give(cup, bob);\n    }\n    function testMold() public {\n        var setAxe = bytes4(keccak256('setAxe(uint256)'));\n        var setCap = bytes4(keccak256('setCap(uint256)'));\n        var setMat = bytes4(keccak256('setMat(uint256)'));\n\n        assertTrue(mom.call(setCap, 0 ether));\n        assertTrue(mom.call(setCap, 5 ether));\n\n        assertTrue(!mom.call(setAxe, ray(2 ether)));\n        assertTrue( mom.call(setMat, ray(2 ether)));\n        assertTrue( mom.call(setAxe, ray(2 ether)));\n        assertTrue(!mom.call(setMat, ray(1 ether)));\n    }\n    function testTune() public {\n        assertEq(vox.how(), 0);\n        mom.setHow(2 * 10 ** 25);\n        assertEq(vox.how(), 2 * 10 ** 25);\n    }\n    function testPriceFeedSetters() public {\n        var setPip = bytes4(keccak256('setPip(address)'));\n        var setPep = bytes4(keccak256('setPep(address)'));\n        var setVox = bytes4(keccak256('setVox(address)'));\n\n        assertTrue(tub.pip() != address(0x1));\n        assertTrue(tub.pep() != address(0x2));\n        assertTrue(tub.vox() != address(0x3));\n        assertTrue(mom.call(setPip, address(0x1)));\n        assertTrue(mom.call(setPep, address(0x2)));\n        assertTrue(mom.call(setVox, address(0x3)));\n        assertTrue(tub.pip() == address(0x1));\n        assertTrue(tub.pep() == address(0x2));\n        assertTrue(tub.vox() == address(0x3));\n    }\n    function testJoinInitial() public {\n        assertEq(skr.totalSupply(),     0 ether);\n        assertEq(skr.balanceOf(this),   0 ether);\n        assertEq(gem.balanceOf(this), 100 ether);\n        tub.join(10 ether);\n        assertEq(skr.balanceOf(this), 10 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        assertEq(gem.balanceOf(tub),  10 ether);\n    }\n    function testJoinExit() public {\n        assertEq(skr.balanceOf(this), 0 ether);\n        assertEq(gem.balanceOf(this), 100 ether);\n        tub.join(10 ether);\n        assertEq(skr.balanceOf(this), 10 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        assertEq(gem.balanceOf(tub),  10 ether);\n\n        tub.exit(5 ether);\n        assertEq(skr.balanceOf(this),  5 ether);\n        assertEq(gem.balanceOf(this), 95 ether);\n        assertEq(gem.balanceOf(tub),   5 ether);\n\n        tub.join(2 ether);\n        assertEq(skr.balanceOf(this),  7 ether);\n        assertEq(gem.balanceOf(this), 93 ether);\n        assertEq(gem.balanceOf(tub),   7 ether);\n\n        tub.exit(1 ether);\n        assertEq(skr.balanceOf(this),  6 ether);\n        assertEq(gem.balanceOf(this), 94 ether);\n        assertEq(gem.balanceOf(tub),   6 ether);\n    }\n    function testFailOverDraw() public {\n        mom.setMat(ray(1 ether));\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        tub.draw(cup, 11 ether);\n    }\n    function testFailOverDrawExcess() public {\n        mom.setMat(ray(1 ether));\n        tub.join(20 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        tub.draw(cup, 11 ether);\n    }\n    function testDraw() public {\n        mom.setMat(ray(1 ether));\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        assertEq(sai.balanceOf(this),  0 ether);\n        tub.draw(cup, 10 ether);\n        assertEq(sai.balanceOf(this), 10 ether);\n    }\n    function testWipe() public {\n        mom.setMat(ray(1 ether));\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 10 ether);\n\n        assertEq(sai.balanceOf(this), 10 ether);\n        tub.wipe(cup, 5 ether);\n        assertEq(sai.balanceOf(this),  5 ether);\n    }\n    function testUnsafe() public {\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 9 ether);\n\n        assertTrue(tub.safe(cup));\n        mark(1 ether / 2);\n        assertTrue(!tub.safe(cup));\n    }\n    function testBiteUnderParity() public {\n        assertEq(uint(tub.axe()), uint(ray(1 ether)));  // 100% collateralisation limit\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 5 ether);           // 200% collateralisation\n        mark(1 ether / 4);                // 50% collateralisation\n\n        assertEq(tap.fog(), uint(0));\n        tub.bite(cup);\n        assertEq(tap.fog(), uint(10 ether));\n    }\n    function testBiteOverParity() public {\n        mom.setMat(ray(2 ether));  // require 200% collateralisation\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        tub.draw(cup, 4 ether);  // 250% collateralisation\n        assertTrue(tub.safe(cup));\n        mark(1 ether / 2);       // 125% collateralisation\n        assertTrue(!tub.safe(cup));\n\n        assertEq(tub.din(),    4 ether);\n        assertEq(tub.tab(cup), 4 ether);\n        assertEq(tap.fog(),    0 ether);\n        assertEq(tap.woe(),    0 ether);\n        tub.bite(cup);\n        assertEq(tub.din(),    0 ether);\n        assertEq(tub.tab(cup), 0 ether);\n        assertEq(tap.fog(),    8 ether);\n        assertEq(tap.woe(),    4 ether);\n\n        // cdp should now be safe with 0 sai debt and 2 skr remaining\n        var skr_before = skr.balanceOf(this);\n        tub.free(cup, 1 ether);\n        assertEq(skr.balanceOf(this) - skr_before, 1 ether);\n    }\n    function testLock() public {\n        tub.join(10 ether);\n        var cup = tub.open();\n\n        assertEq(skr.balanceOf(tub),  0 ether);\n        tub.lock(cup, 10 ether);\n        assertEq(skr.balanceOf(tub), 10 ether);\n    }\n    function testFree() public {\n        mom.setMat(ray(2 ether));  // require 200% collateralisation\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 4 ether);  // 250% collateralisation\n\n        var skr_before = skr.balanceOf(this);\n        tub.free(cup, 2 ether);  // 225%\n        assertEq(skr.balanceOf(this) - skr_before, 2 ether);\n    }\n    function testFailFreeToUnderCollat() public {\n        mom.setMat(ray(2 ether));  // require 200% collateralisation\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 4 ether);  // 250% collateralisation\n\n        tub.free(cup, 3 ether);  // 175% -- fails\n    }\n    function testFailDrawOverDebtCeiling() public {\n        mom.setCap(4 ether);\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        tub.draw(cup, 5 ether);\n    }\n    function testDebtCeiling() public {\n        mom.setCap(5 ether);\n        mom.setMat(ray(2 ether));  // require 200% collat\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        tub.draw(cup, 5 ether);          // 200% collat, full debt ceiling\n        mark(1 ether / 2);  // 100% collat\n\n        assertEq(tub.air(), uint(10 ether));\n        assertEq(tap.fog(), uint(0 ether));\n        tub.bite(cup);\n        assertEq(tub.air(), uint(0 ether));\n        assertEq(tap.fog(), uint(10 ether));\n\n        tub.join(10 ether);\n        // skr hasn't been diluted yet so still 1:1 skr:gem\n        assertEq(skr.balanceOf(this), 10 ether);\n    }\n}\n\ncontract CageTest is SaiTestBase {\n    // ensure cage sets the settle prices right\n    function cageSetup() public returns (bytes32) {\n        mom.setCap(5 ether);            // 5 sai debt ceiling\n        mark(1 ether);   // price 1:1 gem:ref\n        mom.setMat(ray(2 ether));       // require 200% collat\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 5 ether);       // 200% collateralisation\n\n        return cup;\n    }\n    function testCageSafeOverCollat() public {\n        cageSetup();\n\n        assertEq(top.fix(), 0);\n        assertEq(tub.fit(), 0);\n        assertEq(tap.woe(), 0);         // no bad debt\n        assertEq(tub.pie(), 10 ether);\n\n        tub.join(20 ether);   // give us some more skr\n        mark(1 ether);\n        top.cage();\n\n        assertEq(tub.din(),      5 ether);  // debt remains in tub\n        assertEq(wad(top.fix()), 1 ether);  // sai redeems 1:1 with gem\n        assertEq(wad(tub.fit()), 1 ether);  // skr redeems 1:1 with gem just before pushing gem to tub\n\n        assertEq(gem.balanceOf(tap),  5 ether);  // saved for sai\n        assertEq(gem.balanceOf(tub), 25 ether);  // saved for skr\n    }\n    function testCageUnsafeOverCollat() public {\n        cageSetup();\n\n        assertEq(top.fix(), 0);\n        assertEq(tub.fit(), 0);\n        assertEq(tub.per(), ray(1 ether));\n\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(3 ether, 4 ether);\n        mark(price);\n        top.cage();        // 150% collat\n\n        assertEq(top.fix(), rdiv(1 ether, price));  // sai redeems 4:3 with gem\n        assertEq(tub.fit(), ray(price));                 // skr redeems 1:1 with gem just before pushing gem to tub\n\n        // gem needed for sai is 5 * 4 / 3\n        var saved = rmul(5 ether, rdiv(WAD, price));\n        assertEq(gem.balanceOf(tap),  saved);             // saved for sai\n        assertEq(gem.balanceOf(tub),  30 ether - saved);  // saved for skr\n    }\n    function testCageAtCollat() public {\n        cageSetup();\n\n        assertEq(top.fix(), 0);\n        assertEq(tub.fit(), 0);\n        assertEq(tub.per(), ray(1 ether));\n\n        var price = wdiv(1 ether, 2 ether);  // 100% collat\n        mark(price);\n        top.cage();\n\n        assertEq(top.fix(), ray(2 ether));  // sai redeems 1:2 with gem, 1:1 with ref\n        assertEq(tub.per(), 0);       // skr redeems 1:0 with gem after cage\n    }\n    function testCageAtCollatFreeSkr() public {\n        cageSetup();\n\n        assertEq(top.fix(), 0);\n        assertEq(tub.fit(), 0);\n        assertEq(tub.per(), ray(1 ether));\n\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(1 ether, 2 ether);  // 100% collat\n        mark(price);\n        top.cage();\n\n        assertEq(top.fix(), ray(2 ether));  // sai redeems 1:2 with gem, 1:1 with ref\n        assertEq(tub.fit(), ray(price));       // skr redeems 1:1 with gem just before pushing gem to tub\n    }\n    function testCageUnderCollat() public {\n        cageSetup();\n\n        assertEq(top.fix(), 0);\n        assertEq(tub.fit(), 0);\n        assertEq(tub.per(), ray(1 ether));\n\n        var price = wdiv(1 ether, 4 ether);   // 50% collat\n        mark(price);\n        top.cage();\n\n        assertEq(2 * sai.totalSupply(), gem.balanceOf(tap));\n        assertEq(top.fix(), ray(2 ether));  // sai redeems 1:2 with gem, 2:1 with ref\n        assertEq(tub.per(), 0);       // skr redeems 1:0 with gem after cage\n    }\n    function testCageUnderCollatFreeSkr() public {\n        cageSetup();\n\n        assertEq(top.fix(), 0);\n        assertEq(tub.fit(), 0);\n        assertEq(tub.per(), ray(1 ether));\n\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(1 ether, 4 ether);   // 50% collat\n        mark(price);\n        top.cage();\n\n        assertEq(4 * sai.totalSupply(), gem.balanceOf(tap));\n        assertEq(top.fix(), ray(4 ether));                 // sai redeems 1:4 with gem, 1:1 with ref\n    }\n\n    function testCageNoSai() public {\n        var cup = cageSetup();\n        tub.wipe(cup, 5 ether);\n        assertEq(sai.totalSupply(), 0);\n\n        top.cage();\n        assertEq(top.fix(), ray(1 ether));\n    }\n    function testMock() public {\n        cageSetup();\n        top.cage();\n\n        gem.deposit.value(1000 ether)();\n        gem.approve(tap, uint(-1));\n        tap.mock(1000 ether);\n        assertEq(sai.balanceOf(this), 1005 ether);\n        assertEq(gem.balanceOf(tap),  1005 ether);\n    }\n    function testMockNoSai() public {\n        var cup = cageSetup();\n        tub.wipe(cup, 5 ether);\n        assertEq(sai.totalSupply(), 0);\n\n        top.cage();\n\n        gem.deposit.value(1000 ether)();\n        gem.approve(tap, uint(-1));\n        tap.mock(1000 ether);\n        assertEq(sai.balanceOf(this), 1000 ether);\n        assertEq(gem.balanceOf(tap),  1000 ether);\n    }\n\n    // ensure cash returns the expected amount\n    function testCashSafeOverCollat() public {\n        var cup = cageSetup();\n        mark(1 ether);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(skr.balanceOf(this),  0 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        assertEq(gem.balanceOf(tub),   5 ether);\n        assertEq(gem.balanceOf(tap),   5 ether);\n\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),   0 ether);\n        assertEq(skr.balanceOf(this),   0 ether);\n        assertEq(gem.balanceOf(this),  95 ether);\n        assertEq(gem.balanceOf(tub),    5 ether);\n\n        assertEq(tub.ink(cup), 10 ether);\n        tub.bite(cup);\n        assertEq(tub.ink(cup), 5 ether);\n        tub.free(cup, tub.ink(cup));\n        assertEq(skr.balanceOf(this),   5 ether);\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testCashSafeOverCollatWithFreeSkr() public {\n        var cup = cageSetup();\n        tub.join(20 ether);   // give us some more skr\n        mark(1 ether);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(skr.balanceOf(this), 20 ether);\n        assertEq(gem.balanceOf(this), 70 ether);\n        assertEq(gem.balanceOf(tub),  25 ether);\n        assertEq(gem.balanceOf(tap),   5 ether);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        tap.vent();\n        top.flow();\n        assertEq(skr.balanceOf(this), 25 ether);\n        tap.cash(sai.balanceOf(this));\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(sai.balanceOf(this),   0 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        tap.vent();\n        assertEq(sai.totalSupply(), 0);\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testFailCashSafeOverCollatWithFreeSkrExitBeforeBail() public {\n        // fails because exit is before bail\n        var cup = cageSetup();\n        tub.join(20 ether);   // give us some more skr\n        mark(1 ether);\n        top.cage();\n\n        tap.cash(sai.balanceOf(this));\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(skr.balanceOf(this), 0 ether);\n        uint256 gemBySAI = 5 ether; // Adding 5 gem from 5 sai\n        uint256 gemBySKR = wdiv(wmul(20 ether, 30 ether - gemBySAI), 30 ether);\n        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);\n\n        assertEq(sai.balanceOf(this), 0);\n        assertEq(sai.totalSupply(), 0);\n        assertEq(sin.totalSupply(), 0);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        tap.vent();\n        top.flow();\n        assertEq(skr.balanceOf(this), 5 ether); // skr retrieved by bail(cup)\n\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(sai.balanceOf(this),   0 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n        assertEq(sai.totalSupply(), 0);\n        assertEq(sin.totalSupply(), 0);\n\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testCashUnsafeOverCollat() public {\n        var cup = cageSetup();\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(3 ether, 4 ether);\n        mark(price);\n        top.cage();        // 150% collat\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(skr.balanceOf(this), 20 ether);\n        assertEq(gem.balanceOf(this), 70 ether);\n\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),   0 ether);\n        assertEq(skr.balanceOf(this),  20 ether);\n\n        uint256 gemBySAI = wdiv(wmul(5 ether, 4 ether), 3 ether);\n        uint256 gemBySKR = 0;\n\n        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);\n        assertEq(gem.balanceOf(tub),  30 ether - gemBySAI - gemBySKR);\n\n        // how much gem should be returned?\n        // there were 10 gems initially, of which 5 were 100% collat\n        // at the cage price, 5 * 4 / 3 are 100% collat,\n        // leaving 10 - 5 * 4 / 3 as excess = 3.333\n        // this should all be returned\n        var ink = tub.ink(cup);\n        var tab = tub.tab(cup);\n        var skrToRecover = sub(ink, wdiv(tab, price));\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n\n        assertEq(skr.balanceOf(this), 20 ether + skrToRecover);\n        assertEq(skr.balanceOf(tub),  0 ether);\n\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        tap.vent();\n        assertEq(skr.totalSupply(), 0);\n        assertEq(sai.totalSupply(), 0);\n    }\n    function testCashAtCollat() public {\n        var cup = cageSetup();\n        var price = wdiv(1 ether, 2 ether);  // 100% collat\n        mark(price);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(skr.balanceOf(this),  0 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),   0 ether);\n        assertEq(skr.balanceOf(this),   0 ether);\n\n        var saved = rmul(5 ether, rdiv(WAD, price));\n\n        assertEq(gem.balanceOf(this),  90 ether + saved);\n        assertEq(gem.balanceOf(tub),   10 ether - saved);\n\n        // how much gem should be returned?\n        // none :D\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        tap.vent();\n        assertEq(skr.totalSupply(), 0);\n        assertEq(sai.totalSupply(), 0);\n    }\n    function testCashAtCollatFreeSkr() public {\n        var cup = cageSetup();\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(1 ether, 2 ether);  // 100% collat\n        mark(price);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),   5 ether);\n        assertEq(skr.balanceOf(this),  20 ether);\n        assertEq(gem.balanceOf(this),  70 ether);\n\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),   0 ether);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testFailCashAtCollatFreeSkrExitBeforeBail() public {\n        var cup = cageSetup();\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(1 ether, 2 ether);  // 100% collat\n        mark(price);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(skr.balanceOf(this), 20 ether);\n        assertEq(gem.balanceOf(this), 70 ether);\n\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),   0 ether);\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(skr.balanceOf(this),   0 ether);\n\n\n        var gemBySAI = wmul(5 ether, 2 ether);\n        var gemBySKR = wdiv(wmul(20 ether, 30 ether - gemBySAI), 30 ether);\n\n        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);\n        assertEq(gem.balanceOf(tub),  30 ether - gemBySAI - gemBySKR);\n\n        assertEq(sai.totalSupply(), 0);\n        assertEq(sin.totalSupply(), 0);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        tap.vent();\n        tub.exit(uint256(skr.balanceOf(this)));\n\n        // Cup did not have skr to free, then the ramaining gem in tub can not be shared as there is not more skr to exit\n        assertEq(gem.balanceOf(this), 70 ether + gemBySAI + gemBySKR);\n        assertEq(gem.balanceOf(tub),  30 ether - gemBySAI - gemBySKR);\n\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testCashUnderCollat() public {\n        var cup = cageSetup();\n        var price = wdiv(1 ether, 4 ether);  // 50% collat\n        mark(price);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(skr.balanceOf(this),  0 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),   0 ether);\n        assertEq(skr.balanceOf(this),   0 ether);\n\n        // get back all 10 gems, which are now only worth 2.5 ref\n        // so you've lost 50% on you sai\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        // how much gem should be returned?\n        // none :D\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        tap.vent();\n        assertEq(skr.totalSupply(), 0);\n        assertEq(sai.totalSupply(), 0);\n    }\n    function testCashUnderCollatFreeSkr() public {\n        var cup = cageSetup();\n        tub.join(20 ether);   // give us some more skr\n        var price = wdiv(1 ether, 4 ether);   // 50% collat\n        mark(price);\n        top.cage();\n\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(gem.balanceOf(this), 70 ether);\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),  0 ether);\n        // returns 20 gems, taken from the free skr,\n        // sai is made whole\n        assertEq(gem.balanceOf(this), 90 ether);\n\n        assertEq(skr.balanceOf(this),  20 ether);\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this)));\n        assertEq(skr.balanceOf(this),   0 ether);\n        // the skr has taken a 50% loss - 10 gems returned from 20 put in\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(gem.balanceOf(tub),    0 ether);\n\n        assertEq(sai.totalSupply(), 0);\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testCashSafeOverCollatAndMock() public {\n        testCashSafeOverCollat();\n        gem.approve(tap, uint(-1));\n        tap.mock(5 ether);\n        assertEq(sai.balanceOf(this), 5 ether);\n        assertEq(gem.balanceOf(this), 95 ether);\n        assertEq(gem.balanceOf(tap), 5 ether);\n    }\n    function testCashSafeOverCollatWithFreeSkrAndMock() public {\n        testCashSafeOverCollatWithFreeSkr();\n        gem.approve(tap, uint(-1));\n        tap.mock(5 ether);\n        assertEq(sai.balanceOf(this), 5 ether);\n        assertEq(gem.balanceOf(this), 95 ether);\n        assertEq(gem.balanceOf(tap), 5 ether);\n    }\n    function testFailCashSafeOverCollatWithFreeSkrExitBeforeBailAndMock() public {\n        testFailCashSafeOverCollatWithFreeSkrExitBeforeBail();\n        gem.approve(tap, uint(-1));\n        tap.mock(5 ether);\n        assertEq(sai.balanceOf(this), 5 ether);\n        assertEq(gem.balanceOf(this), 95 ether);\n        assertEq(gem.balanceOf(tap), 5 ether);\n    }\n\n    function testThreeCupsOverCollat() public {\n        var cup = cageSetup();\n        tub.join(90 ether);   // give us some more skr\n        var cup2 = tub.open(); // open a new cup\n        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI\n        var cup3 = tub.open(); // open a new cup\n        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI\n\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(tub), 100 ether);\n        assertEq(gem.balanceOf(this), 0);\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 50 ether); // locked skr\n\n        uint256 price = 1 ether;\n        mark(price);\n        top.cage();\n\n        assertEq(gem.balanceOf(tap), 5 ether); // Needed to payout 5 sai\n        assertEq(gem.balanceOf(tub), 95 ether);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup)); // 5 skr recovered, and 5 skr burnt\n\n        assertEq(skr.balanceOf(this), 55 ether); // free skr\n        assertEq(skr.balanceOf(tub), 40 ether); // locked skr\n\n        tub.bite(cup2);\n        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 75 ether); // free skr\n        assertEq(skr.balanceOf(tub), 20 ether); // locked skr\n\n        tub.bite(cup3);\n        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 95 ether); // free skr\n        assertEq(skr.balanceOf(tub), 0); // locked skr\n\n        tap.cash(sai.balanceOf(this));\n\n        assertEq(sai.balanceOf(this), 0);\n        assertEq(gem.balanceOf(this), 5 ether);\n\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this))); // exit 95 skr at price 95/95\n\n        assertEq(gem.balanceOf(tub), 0);\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testThreeCupsAtCollat() public {\n        var cup = cageSetup();\n        tub.join(90 ether);   // give us some more skr\n        var cup2 = tub.open(); // open a new cup\n        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI\n        var cup3 = tub.open(); // open a new cup\n        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI\n\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(tub), 100 ether);\n        assertEq(gem.balanceOf(this), 0);\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 50 ether); // locked skr\n\n        var price = wdiv(1 ether, 2 ether);\n        mark(price);\n        top.cage();\n\n        assertEq(gem.balanceOf(tap), 10 ether); // Needed to payout 10 sai\n        assertEq(gem.balanceOf(tub), 90 ether);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup)); // 10 skr burnt\n\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 40 ether); // locked skr\n\n        tub.bite(cup2);\n        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 70 ether); // free skr\n        assertEq(skr.balanceOf(tub), 20 ether); // locked skr\n\n        tub.bite(cup3);\n        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 90 ether); // free skr\n        assertEq(skr.balanceOf(tub), 0); // locked skr\n\n        tap.cash(sai.balanceOf(this));\n\n        assertEq(sai.balanceOf(this), 0);\n        assertEq(gem.balanceOf(this), 10 ether);\n\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this))); // exit 90 skr at price 90/90\n\n        assertEq(gem.balanceOf(tub), 0);\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testThreeCupsUnderCollat() public {\n        var cup = cageSetup();\n        tub.join(90 ether);   // give us some more skr\n        var cup2 = tub.open(); // open a new cup\n        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI\n        var cup3 = tub.open(); // open a new cup\n        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI\n\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(tub), 100 ether);\n        assertEq(gem.balanceOf(this), 0);\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 50 ether); // locked skr\n\n        var price = wdiv(1 ether, 4 ether);\n        mark(price);\n        top.cage();\n\n        assertEq(gem.balanceOf(tap), 20 ether); // Needed to payout 5 sai\n        assertEq(gem.balanceOf(tub), 80 ether);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup)); // No skr is retrieved as the cup doesn't even cover the debt. 10 locked skr in cup are burnt from tub\n\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 40 ether); // locked skr\n\n        tub.bite(cup2);\n        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 70 ether); // free skr\n        assertEq(skr.balanceOf(tub), 20 ether); // locked skr\n\n        tub.bite(cup3);\n        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 90 ether); // free skr\n        assertEq(skr.balanceOf(tub), 0); // locked skr\n\n        tap.cash(sai.balanceOf(this));\n\n        assertEq(sai.balanceOf(this), 0);\n        assertEq(gem.balanceOf(this), 20 ether);\n\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this))); // exit 90 skr at price 80/90\n\n        assertEq(gem.balanceOf(tub), 0);\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(skr.totalSupply(), 0);\n    }\n    function testThreeCupsSKRZeroValue() public {\n        var cup = cageSetup();\n        tub.join(90 ether);   // give us some more skr\n        var cup2 = tub.open(); // open a new cup\n        tub.lock(cup2, 20 ether); // lock collateral but not draw DAI\n        var cup3 = tub.open(); // open a new cup\n        tub.lock(cup3, 20 ether); // lock collateral but not draw DAI\n\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(tub), 100 ether);\n        assertEq(gem.balanceOf(this), 0);\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 50 ether); // locked skr\n\n        var price = wdiv(1 ether, 20 ether);\n        mark(price);\n        top.cage();\n\n        assertEq(gem.balanceOf(tap), 100 ether); // Needed to payout 5 sai\n        assertEq(gem.balanceOf(tub), 0 ether);\n\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup)); // No skr is retrieved as the cup doesn't even cover the debt. 10 locked skr in cup are burnt from tub\n\n        assertEq(skr.balanceOf(this), 50 ether); // free skr\n        assertEq(skr.balanceOf(tub), 40 ether); // locked skr\n\n        tub.bite(cup2);\n        tub.free(cup2, tub.ink(cup2)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 70 ether); // free skr\n        assertEq(skr.balanceOf(tub), 20 ether); // locked skr\n\n        tub.bite(cup3);\n        tub.free(cup3, tub.ink(cup3)); // 20 skr recovered\n\n        assertEq(skr.balanceOf(this), 90 ether); // free skr\n        assertEq(skr.balanceOf(tub), 0); // locked skr\n\n        tap.cash(sai.balanceOf(this));\n\n        assertEq(sai.balanceOf(this), 0);\n        assertEq(gem.balanceOf(this), 100 ether);\n\n        tap.vent();\n        top.flow();\n        tub.exit(uint256(skr.balanceOf(this))); // exit 90 skr at price 0/90\n\n        assertEq(gem.balanceOf(tub), 0);\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(this), 100 ether);\n        assertEq(skr.totalSupply(), 0);\n    }\n\n    function testPeriodicFixValue() public {\n        cageSetup();\n\n        assertEq(gem.balanceOf(tap), 0);\n        assertEq(gem.balanceOf(tub), 10 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        assertEq(skr.balanceOf(this), 0 ether); // free skr\n        assertEq(skr.balanceOf(tub), 10 ether); // locked skr\n\n        FakePerson person = new FakePerson(tap);\n        sai.transfer(person, 2.5 ether); // Transfer half of SAI balance to the other user\n\n        var price = rdiv(9 ether, 8 ether);\n        mark(price);\n        top.cage();\n\n        assertEq(gem.balanceOf(tap), rmul(5 ether, top.fix())); // Needed to payout 5 sai\n        assertEq(gem.balanceOf(tub), sub(10 ether, rmul(5 ether, top.fix())));\n\n        tap.cash(sai.balanceOf(this));\n\n        assertEq(sai.balanceOf(this),     0 ether);\n        assertEq(sai.balanceOf(person), 2.5 ether);\n        assertEq(gem.balanceOf(this), add(90 ether, rmul(2.5 ether, top.fix())));\n\n        person.cash();\n    }\n\n    function testCageExitAfterPeriod() public {\n        var cup = cageSetup();\n        mom.setMat(ray(1 ether));  // 100% collat limit\n        tub.free(cup, 5 ether);  // 100% collat\n\n        assertEq(uint(top.caged()), 0);\n        top.cage();\n        assertEq(uint(top.caged()), vox.era());\n\n        // exit fails because ice != 0 && fog !=0 and not enough time passed\n        assertTrue(!tub.call(bytes4(keccak256('exit(uint256)')), 5 ether));\n\n        top.setCooldown(1 days);\n        warp(1 days);\n        assertTrue(!tub.call(bytes4(keccak256('exit(uint256)')), 5 ether));\n\n        warp(1 seconds);\n        top.flow();\n        assertEq(skr.balanceOf(this), 5 ether);\n        assertEq(gem.balanceOf(this), 90 ether);\n        assertTrue(tub.call(bytes4(keccak256('exit(uint256)')), 4 ether));\n        assertEq(skr.balanceOf(this), 1 ether);\n        // n.b. we don't get back 4 as there is still skr in the cup\n        assertEq(gem.balanceOf(this), 92 ether);\n\n        // now we can cash in our sai\n        assertEq(sai.balanceOf(this), 5 ether);\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this), 0 ether);\n        assertEq(gem.balanceOf(this), 97 ether);\n\n        // the remaining gem can be claimed only if the cup skr is burned\n        assertEq(tub.air(), 5 ether);\n        assertEq(tap.fog(), 0 ether);\n        assertEq(tub.din(), 5 ether);\n        assertEq(tap.woe(), 0 ether);\n        tub.bite(cup);\n        assertEq(tub.air(), 0 ether);\n        assertEq(tap.fog(), 5 ether);\n        assertEq(tub.din(), 0 ether);\n        assertEq(tap.woe(), 5 ether);\n\n        tap.vent();\n        assertEq(tap.fog(), 0 ether);\n\n        // now this remaining 1 skr will claim all the remaining 3 ether.\n        // this is why exiting early is bad if you want to maximise returns.\n        // if we had exited with all the skr earlier, there would be 2.5 gem\n        // trapped in the tub.\n        tub.exit(1 ether);\n        assertEq(skr.balanceOf(this),   0 ether);\n        assertEq(gem.balanceOf(this), 100 ether);\n    }\n\n    function testShutEmptyCup() public {\n        var cup = tub.open();\n        var (lad,,,) = tub.cups(cup);\n        assertEq(lad, this);\n        tub.shut(cup);\n        (lad,,,) = tub.cups(cup);\n        assertEq(lad, 0);\n    }\n}\n\ncontract LiquidationTest is SaiTestBase {\n    function liq(bytes32 cup) internal returns (uint256) {\n        // compute the liquidation price of a cup\n        var jam = rmul(tub.ink(cup), tub.per());  // this many eth\n        var con = rmul(tub.tab(cup), vox.par());  // this much ref debt\n        var min = rmul(con, tub.mat());        // minimum ref debt\n        return wdiv(min, jam);\n    }\n    function testLiq() public {\n        mom.setCap(100 ether);\n        mark(2 ether);\n\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 10 ether);        // 200% collateralisation\n\n        mom.setMat(ray(1 ether));         // require 100% collateralisation\n        assertEq(liq(cup), 1 ether);\n\n        mom.setMat(ray(3 ether / 2));     // require 150% collateralisation\n        assertEq(liq(cup), wdiv(3 ether, 2 ether));\n\n        mark(6 ether);\n        assertEq(liq(cup), wdiv(3 ether, 2 ether));\n\n        tub.draw(cup, 30 ether);\n        assertEq(liq(cup), 6 ether);\n\n        tub.join(10 ether);\n        assertEq(liq(cup), 6 ether);\n\n        tub.lock(cup, 10 ether);  // now 40 drawn on 20 gem == 120 ref\n        assertEq(liq(cup), 3 ether);\n    }\n    function collat(bytes32 cup) internal returns (uint256) {\n        // compute the collateralised fraction of a cup\n        var pro = rmul(tub.ink(cup), tub.tag());\n        var con = rmul(tub.tab(cup), vox.par());\n        return wdiv(pro, con);\n    }\n    function testCollat() public {\n        mom.setCap(100 ether);\n        mark(2 ether);\n\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 10 ether);\n\n        assertEq(collat(cup), 2 ether);  // 200%\n\n        mark(4 ether);\n        assertEq(collat(cup), 4 ether);  // 400%\n\n        tub.draw(cup, 15 ether);\n        assertEq(collat(cup), wdiv(8 ether, 5 ether));  // 160%\n\n        mark(5 ether);\n        tub.free(cup, 5 ether);\n        assertEq(collat(cup), 1 ether);  // 100%\n\n        mark(4 ether);\n        assertEq(collat(cup), wdiv(4 ether, 5 ether));  // 80%\n\n        tub.wipe(cup, 9 ether);\n        assertEq(collat(cup), wdiv(5 ether, 4 ether));  // 125%\n    }\n\n    function testBustMint() public {\n        mom.setCap(100 ether);\n        mom.setMat(ray(wdiv(3 ether, 2 ether)));  // 150% liq limit\n        mark(2 ether);\n\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n\n        mark(3 ether);\n        tub.draw(cup, 16 ether);  // 125% collat\n        mark(2 ether);\n\n        assertTrue(!tub.safe(cup));\n        tub.bite(cup);\n        // 20 ref of gem on 16 ref of sai\n        // 125%\n        // 100% = 16ref of gem == 8 gem\n        assertEq(tap.fog(), 8 ether);\n\n        // 8 skr for sale\n        assertEq(tub.per(), ray(1 ether));\n\n        // get 2 skr, pay 4 sai (25% of the debt)\n        var sai_before = sai.balanceOf(this);\n        var skr_before = skr.balanceOf(this);\n        assertEq(sai_before, 16 ether);\n        tap.bust(2 ether);\n        var sai_after = sai.balanceOf(this);\n        var skr_after = skr.balanceOf(this);\n        assertEq(sai_before - sai_after, 4 ether);\n        assertEq(skr_after - skr_before, 2 ether);\n\n        // price drop. now remaining 6 skr cannot cover bad debt (12 sai)\n        mark(1 ether);\n\n        // get 6 skr, pay 6 sai\n        tap.bust(6 ether);\n        // no more skr remaining to sell\n        assertEq(tap.fog(), 0);\n        // but skr supply unchanged\n        assertEq(skr.totalSupply(), 10 ether);\n\n        // now skr will be minted\n        tap.bust(2 ether);\n        assertEq(skr.totalSupply(), 12 ether);\n    }\n    function testBustNoMint() public {\n        mom.setCap(1000 ether);\n        mom.setMat(ray(2 ether));    // 200% liq limit\n        mom.setAxe(ray(1.5 ether));  // 150% liq penalty\n        mark(20 ether);\n\n        tub.join(10 ether);\n        var cup = tub.open();\n        tub.lock(cup, 10 ether);\n        tub.draw(cup, 100 ether);  // 200 % collat\n\n        mark(15 ether);\n        tub.bite(cup);\n\n        // nothing remains in the cup\n        assertEq(tub.tab(cup), 0);\n        assertEq(tub.ink(cup), 0);\n\n        // all collateral is now fog\n        assertEq(tap.fog(), 10 ether);\n        assertEq(tap.woe(), 100 ether);\n\n        // the fog is worth 150 sai and the woe is worth 100 sai.\n        // If all the fog is sold, there will be a sai surplus.\n\n        // get some more sai to buy with\n        tub.join(10 ether);\n        var mug = tub.open();\n        tub.lock(mug, 10 ether);\n        tub.draw(mug, 50 ether);\n\n        tap.bust(10 ether);\n        assertEq(sai.balanceOf(this), 0 ether);\n        assertEq(skr.balanceOf(this), 10 ether);\n        assertEq(tap.fog(), 0 ether);\n        assertEq(tap.woe(), 0 ether);\n        assertEq(tap.joy(), 50 ether);\n\n        // joy is available through boom\n        assertEq(tap.bid(1 ether), 15 ether);\n        tap.boom(2 ether);\n        assertEq(sai.balanceOf(this), 30 ether);\n        assertEq(skr.balanceOf(this),  8 ether);\n        assertEq(tap.fog(), 0 ether);\n        assertEq(tap.woe(), 0 ether);\n        assertEq(tap.joy(), 20 ether);\n    }\n}\n\ncontract TapTest is SaiTestBase {\n    function testTapSetup() public {\n        assertEq(sai.balanceOf(tap), tap.joy());\n        assertEq(sin.balanceOf(tap), tap.woe());\n        assertEq(skr.balanceOf(tap), tap.fog());\n\n        assertEq(tap.joy(), 0);\n        assertEq(tap.woe(), 0);\n        assertEq(tap.fog(), 0);\n\n        sai.mint(tap, 3);\n        sin.mint(tap, 4);\n        skr.mint(tap, 5);\n\n        assertEq(tap.joy(), 3);\n        assertEq(tap.woe(), 4);\n        assertEq(tap.fog(), 5);\n    }\n    // boom (flap) is surplus sale (sai for skr->burn)\n    function testTapBoom() public {\n        sai.mint(tap, 50 ether);\n        tub.join(60 ether);\n\n        assertEq(sai.balanceOf(this),  0 ether);\n        assertEq(skr.balanceOf(this), 60 ether);\n        tap.boom(50 ether);\n        assertEq(sai.balanceOf(this), 50 ether);\n        assertEq(skr.balanceOf(this), 10 ether);\n        assertEq(tap.joy(), 0);\n    }\n    function testFailTapBoomOverJoy() public {\n        sai.mint(tap, 50 ether);\n        tub.join(60 ether);\n        tap.boom(51 ether);\n    }\n    function testTapBoomHeals() public {\n        sai.mint(tap, 60 ether);\n        sin.mint(tap, 50 ether);\n        tub.join(10 ether);\n\n        tap.boom(0 ether);\n        assertEq(tap.joy(), 10 ether);\n    }\n    function testFailTapBoomNetWoe() public {\n        sai.mint(tap, 50 ether);\n        sin.mint(tap, 60 ether);\n        tub.join(10 ether);\n        tap.boom(1 ether);\n    }\n    function testTapBoomBurnsSkr() public {\n        sai.mint(tap, 50 ether);\n        tub.join(60 ether);\n\n        assertEq(skr.totalSupply(), 60 ether);\n        tap.boom(20 ether);\n        assertEq(skr.totalSupply(), 40 ether);\n    }\n    function testTapBoomIncreasesPer() public {\n        sai.mint(tap, 50 ether);\n        tub.join(60 ether);\n\n        assertEq(tub.per(), ray(1 ether));\n        tap.boom(30 ether);\n        assertEq(tub.per(), ray(2 ether));\n    }\n    function testTapBoomMarkDep() public {\n        sai.mint(tap, 50 ether);\n        tub.join(50 ether);\n\n        mark(2 ether);\n        tap.boom(10 ether);\n        assertEq(sai.balanceOf(this), 20 ether);\n        assertEq(sai.balanceOf(tap),  30 ether);\n        assertEq(skr.balanceOf(this), 40 ether);\n    }\n    function testTapBoomPerDep() public {\n        sai.mint(tap, 50 ether);\n        tub.join(50 ether);\n\n        assertEq(tub.per(), ray(1 ether));\n        skr.mint(50 ether);  // halves per\n        assertEq(tub.per(), ray(.5 ether));\n\n        tap.boom(10 ether);\n        assertEq(sai.balanceOf(this),  5 ether);\n        assertEq(sai.balanceOf(tap),  45 ether);\n        assertEq(skr.balanceOf(this), 90 ether);\n    }\n    // flip is collateral sale (skr for sai)\n    function testTapBustFlip() public {\n        sai.mint(50 ether);\n        tub.join(50 ether);\n        skr.push(tap, 50 ether);\n        assertEq(tap.fog(), 50 ether);\n\n        assertEq(skr.balanceOf(this),  0 ether);\n        assertEq(sai.balanceOf(this), 50 ether);\n        tap.bust(30 ether);\n        assertEq(skr.balanceOf(this), 30 ether);\n        assertEq(sai.balanceOf(this), 20 ether);\n    }\n    function testFailTapBustFlipOverFog() public { // FAIL\n        sai.mint(50 ether);\n        tub.join(50 ether);\n        skr.push(tap, 50 ether);\n\n        tap.bust(51 ether);\n    }\n    function testTapBustFlipHealsNetJoy() public {\n        sai.mint(tap, 10 ether);\n        sin.mint(tap, 20 ether);\n        tub.join(50 ether);\n        skr.push(tap, 50 ether);\n\n        sai.mint(15 ether);\n        tap.bust(15 ether);\n        assertEq(tap.joy(), 5 ether);\n        assertEq(tap.woe(), 0 ether);\n    }\n    function testTapBustFlipHealsNetWoe() public {\n        sai.mint(tap, 10 ether);\n        sin.mint(tap, 20 ether);\n        tub.join(50 ether);\n        skr.push(tap, 50 ether);\n\n        sai.mint(5 ether);\n        tap.bust(5 ether);\n        assertEq(tap.joy(), 0 ether);\n        assertEq(tap.woe(), 5 ether);\n    }\n    // flop is debt sale (woe->skr for sai)\n    function testTapBustFlop() public {\n        tub.join(50 ether);  // avoid per=1 init case\n        sai.mint(100 ether);\n        sin.mint(tap, 50 ether);\n        assertEq(tap.woe(), 50 ether);\n\n        assertEq(skr.balanceOf(this),  50 ether);\n        assertEq(sai.balanceOf(this), 100 ether);\n        tap.bust(50 ether);\n        assertEq(skr.balanceOf(this), 100 ether);\n        assertEq(sai.balanceOf(this),  75 ether);\n    }\n    function testFailTapBustFlopNetJoy() public {\n        tub.join(50 ether);  // avoid per=1 init case\n        sai.mint(100 ether);\n        sin.mint(tap, 50 ether);\n        sai.mint(tap, 100 ether);\n\n        tap.bust(1);  // anything but zero should fail\n    }\n    function testTapBustFlopMintsSkr() public {\n        tub.join(50 ether);  // avoid per=1 init case\n        sai.mint(100 ether);\n        sin.mint(tap, 50 ether);\n\n        assertEq(skr.totalSupply(),  50 ether);\n        tap.bust(20 ether);\n        assertEq(skr.totalSupply(),  70 ether);\n    }\n    function testTapBustFlopDecreasesPer() public {\n        tub.join(50 ether);  // avoid per=1 init case\n        sai.mint(100 ether);\n        sin.mint(tap, 50 ether);\n\n        assertEq(tub.per(), ray(1 ether));\n        tap.bust(50 ether);\n        assertEq(tub.per(), ray(.5 ether));\n    }\n\n    function testTapBustAsk() public {\n        tub.join(50 ether);\n        assertEq(tap.ask(50 ether), 50 ether);\n\n        skr.mint(50 ether);\n        assertEq(tap.ask(50 ether), 25 ether);\n\n        skr.mint(100 ether);\n        assertEq(tap.ask(50 ether), 12.5 ether);\n\n        skr.burn(175 ether);\n        assertEq(tap.ask(50 ether), 100 ether);\n\n        skr.mint(25 ether);\n        assertEq(tap.ask(50 ether), 50 ether);\n\n        skr.mint(10 ether);\n        // per = 5 / 6\n        assertEq(tap.ask(60 ether), 50 ether);\n\n        skr.mint(30 ether);\n        // per = 5 / 9\n        assertEq(tap.ask(90 ether), 50 ether);\n\n        skr.mint(10 ether);\n        // per = 1 / 2\n        assertEq(tap.ask(100 ether), 50 ether);\n    }\n    // flipflop is debt sale when collateral present\n    function testTapBustFlipFlopRounding() public {\n        tub.join(50 ether);  // avoid per=1 init case\n        sai.mint(100 ether);\n        sin.mint(tap, 100 ether);\n        skr.push(tap,  50 ether);\n        assertEq(tap.joy(),   0 ether);\n        assertEq(tap.woe(), 100 ether);\n        assertEq(tap.fog(),  50 ether);\n\n        assertEq(skr.balanceOf(this),   0 ether);\n        assertEq(sai.balanceOf(this), 100 ether);\n        assertEq(skr.totalSupply(),    50 ether);\n\n        assertEq(tub.per(), ray(1 ether));\n        assertEq(tap.s2s(), ray(1 ether));\n        assertEq(tub.tag(), ray(1 ether));\n        assertEq(tap.ask(60 ether), 60 ether);\n        tap.bust(60 ether);\n        assertEq(tub.per(), rdiv(5, 6));\n        assertEq(tap.s2s(), rdiv(5, 6));\n        assertEq(tub.tag(), rdiv(5, 6));\n        // non ray prices would give small rounding error because wad math\n        assertEq(tap.ask(60 ether), 50 ether);\n        assertEq(skr.totalSupply(),    60 ether);\n        assertEq(tap.fog(),             0 ether);\n        assertEq(skr.balanceOf(this),  60 ether);\n        assertEq(sai.balanceOf(this),  50 ether);\n    }\n    function testTapBustFlipFlop() public {\n        tub.join(50 ether);  // avoid per=1 init case\n        sai.mint(100 ether);\n        sin.mint(tap, 100 ether);\n        skr.push(tap,  50 ether);\n        assertEq(tap.joy(),   0 ether);\n        assertEq(tap.woe(), 100 ether);\n        assertEq(tap.fog(),  50 ether);\n\n        assertEq(skr.balanceOf(this),   0 ether);\n        assertEq(sai.balanceOf(this), 100 ether);\n        assertEq(skr.totalSupply(),    50 ether);\n        assertEq(tub.per(), ray(1 ether));\n        tap.bust(80 ether);\n        assertEq(tub.per(), rdiv(5, 8));\n        assertEq(skr.totalSupply(),    80 ether);\n        assertEq(tap.fog(),             0 ether);\n        assertEq(skr.balanceOf(this),  80 ether);\n        assertEq(sai.balanceOf(this),  50 ether);  // expected 50, actual 50 ether + 2???!!!\n    }\n}\n\ncontract TaxTest is SaiTestBase {\n    function testEraInit() public {\n        assertEq(uint(vox.era()), now);\n    }\n    function testEraWarp() public {\n        warp(20);\n        assertEq(uint(vox.era()), now + 20);\n    }\n    function taxSetup() public returns (bytes32 cup) {\n        mark(10 ether);\n        gem.deposit.value(1000 ether)();\n\n        mom.setCap(1000 ether);\n        mom.setTax(1000000564701133626865910626);  // 5% / day\n        cup = tub.open();\n        tub.join(100 ether);\n        tub.lock(cup, 100 ether);\n        tub.draw(cup, 100 ether);\n    }\n    function testTaxEra() public {\n        var cup = taxSetup();\n        assertEq(tub.tab(cup), 100 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 105 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 110.25 ether);\n    }\n    // rum doesn't change on drip\n    function testTaxRum() public {\n        taxSetup();\n        assertEq(tub.rum(),    100 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.rum(),    100 ether);\n    }\n    // din increases on drip\n    function testTaxDin() public {\n        taxSetup();\n        assertEq(tub.din(),    100 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.din(),    105 ether);\n    }\n    // Tax accumulates as sai surplus, and CDP debt\n    function testTaxJoy() public {\n        var cup = taxSetup();\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),      0 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),      5 ether);\n    }\n    function testTaxJoy2() public {\n        var cup = taxSetup();\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),      0 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),      5 ether);\n        // now ensure din != rum\n        tub.wipe(cup, 5 ether);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),      5 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),     10 ether);\n    }\n    function testTaxJoy3() public {\n        var cup = taxSetup();\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),      0 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),      5 ether);\n        // now ensure rum changes\n        tub.wipe(cup, 5 ether);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),      5 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),     10 ether);\n        // and ensure the last rum != din either\n        tub.wipe(cup, 5 ether);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),     10 ether);\n        warp(1 days);\n        tub.drip();\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),     15 ether);\n    }\n    function testTaxDraw() public {\n        var cup = taxSetup();\n        warp(1 days);\n        assertEq(tub.tab(cup), 105 ether);\n        tub.draw(cup, 100 ether);\n        assertEq(tub.tab(cup), 205 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 215.25 ether);\n    }\n    function testTaxWipe() public {\n        var cup = taxSetup();\n        warp(1 days);\n        assertEq(tub.tab(cup), 105 ether);\n        tub.wipe(cup, 50 ether);\n        assertEq(tub.tab(cup), 55 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 57.75 ether);\n    }\n    // collected fees are available through boom\n    function testTaxBoom() public {\n        taxSetup();\n        warp(1 days);\n        // should have 5 sai available == 0.5 skr\n        tub.join(0.5 ether);  // get some unlocked skr\n\n        assertEq(skr.totalSupply(),   100.5 ether);\n        assertEq(sai.balanceOf(tap),    0 ether);\n        assertEq(sin.balanceOf(tap),    0 ether);\n        assertEq(sai.balanceOf(this), 100 ether);\n        tub.drip();\n        assertEq(sai.balanceOf(tap),    5 ether);\n        tap.boom(0.5 ether);\n        assertEq(skr.totalSupply(),   100 ether);\n        assertEq(sai.balanceOf(tap),    0 ether);\n        assertEq(sin.balanceOf(tap),    0 ether);\n        assertEq(sai.balanceOf(this), 105 ether);\n    }\n    // Tax can flip a cup to unsafe\n    function testTaxSafe() public {\n        var cup = taxSetup();\n        mark(1 ether);\n        assertTrue(tub.safe(cup));\n        warp(1 days);\n        assertTrue(!tub.safe(cup));\n    }\n    function testTaxBite() public {\n        var cup = taxSetup();\n        mark(1 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 105 ether);\n        tub.bite(cup);\n        assertEq(tub.tab(cup),   0 ether);\n        assertEq(tap.woe(),    105 ether);\n    }\n    function testTaxBiteRounding() public {\n        var cup = taxSetup();\n        mark(1 ether);\n        mom.setMat(ray(1.5 ether));\n        mom.setAxe(ray(1.4 ether));\n        mom.setTax(ray(1.000000001547126 ether));\n        // log_named_uint('tab', tub.tab(cup));\n        // log_named_uint('sin', tub.din());\n        for (uint i=0; i<=50; i++) {\n            warp(10);\n            // log_named_uint('tab', tub.tab(cup));\n            // log_named_uint('sin', tub.din());\n        }\n        uint256 debtAfterWarp = rmul(100 ether, rpow(tub.tax(), 510));\n        assertEq(tub.tab(cup), debtAfterWarp);\n        tub.bite(cup);\n        assertEq(tub.tab(cup), 0 ether);\n        assertEq(tap.woe(), rmul(100 ether, rpow(tub.tax(), 510)));\n    }\n    function testTaxBail() public {\n        var cup = taxSetup();\n        warp(1 days);\n        tub.drip();\n        mark(10 ether);\n        top.cage();\n\n        warp(1 days);  // should have no effect\n        tub.drip();\n\n        assertEq(skr.balanceOf(this),  0 ether);\n        assertEq(skr.balanceOf(tub), 100 ether);\n        tub.bite(cup);\n        tub.free(cup, tub.ink(cup));\n        assertEq(skr.balanceOf(this), 89.5 ether);\n        assertEq(skr.balanceOf(tub),     0 ether);\n\n        assertEq(sai.balanceOf(this),  100 ether);\n        assertEq(gem.balanceOf(this), 1000 ether);\n        tap.cash(sai.balanceOf(this));\n        assertEq(sai.balanceOf(this),    0 ether);\n        assertEq(gem.balanceOf(this), 1010 ether);\n    }\n    function testTaxCage() public {\n        // after cage, un-distributed tax revenue remains as joy - sai\n        // surplus in the tap. The remaining joy, plus all outstanding\n        // sai, balances the sin debt in the tub, plus any debt (woe) in\n        // the tap.\n\n        // The effect of this is that joy remaining in tap is\n        // effectively distributed to all skr holders.\n        var cup = taxSetup();\n        warp(1 days);\n        mark(10 ether);\n\n        assertEq(tap.joy(), 0 ether);\n        top.cage();                // should drip up to date\n        assertEq(tap.joy(), 5 ether);\n        warp(1 days);  tub.drip();  // should have no effect\n        assertEq(tap.joy(), 5 ether);\n\n        var owe = tub.tab(cup);\n        assertEq(owe, 105 ether);\n        assertEq(tub.din(), owe);\n        assertEq(tap.woe(), 0);\n        tub.bite(cup);\n        assertEq(tub.din(), 0);\n        assertEq(tap.woe(), owe);\n        assertEq(tap.joy(), 5 ether);\n    }\n}\n\ncontract WayTest is SaiTestBase {\n    function waySetup() public returns (bytes32 cup) {\n        mark(10 ether);\n        gem.deposit.value(1000 ether)();\n\n        mom.setCap(1000 ether);\n\n        cup = tub.open();\n        tub.join(100 ether);\n        tub.lock(cup, 100 ether);\n        tub.draw(cup, 100 ether);\n    }\n    // what does way actually do?\n    // it changes the value of sai relative to ref\n    // way > 1 -> par increasing, more ref per sai\n    // way < 1 -> par decreasing, less ref per sai\n\n    // this changes the safety level of cups,\n    // affecting `draw`, `wipe`, `free` and `bite`\n\n    // if way < 1, par is decreasing and the con (in ref)\n    // of a cup is decreasing, so cup holders need\n    // less ref to wipe (but the same sai)\n    // This makes cups *more* collateralised with time.\n    function testTau() public {\n        assertEq(uint(vox.era()), now);\n        assertEq(uint(vox.tau()), now);\n    }\n    function testWayPar() public {\n        mom.setWay(999999406327787478619865402);  // -5% / day\n\n        assertEq(wad(vox.par()), 1.00 ether);\n        warp(1 days);\n        assertEq(wad(vox.par()), 0.95 ether);\n\n        mom.setWay(1000000021979553151239153027);  // 200% / year\n        warp(1 years);\n        assertEq(wad(vox.par()), 1.90 ether);\n    }\n    function testWayDecreasingPrincipal() public {\n        var cup = waySetup();\n        mark(0.98 ether);\n        assertTrue(!tub.safe(cup));\n\n        mom.setWay(999999406327787478619865402);  // -5% / day\n        warp(1 days);\n        assertTrue(tub.safe(cup));\n    }\n    // `cage` is slightly affected: the cage price is\n    // now in *sai per gem*, where before ref per gem\n    // was equivalent.\n    // `bail` is unaffected, as all values are in sai.\n    function testWayCage() public {\n        waySetup();\n\n        mom.setWay(1000000021979553151239153027);  // 200% / year\n        warp(1 years);  // par now 2\n\n        // we have 100 sai\n        // gem is worth 10 ref\n        // sai is worth 2 ref\n        // we should get back 100 / (10 / 2) = 20 gem\n\n        top.cage();\n\n        assertEq(gem.balanceOf(this), 1000 ether);\n        assertEq(sai.balanceOf(this),  100 ether);\n        assertEq(sai.balanceOf(tap),     0 ether);\n        tap.cash(sai.balanceOf(this));\n        assertEq(gem.balanceOf(this), 1020 ether);\n        assertEq(sai.balanceOf(this),    0 ether);\n        assertEq(sai.balanceOf(tap),     0 ether);\n    }\n\n    // `boom` and `bust` as par is now needed to determine\n    // the skr / sai price.\n    function testWayBust() public {\n        var cup = waySetup();\n        mark(0.5 ether);\n        tub.bite(cup);\n\n        assertEq(tap.joy(),   0 ether);\n        assertEq(tap.woe(), 100 ether);\n        assertEq(tap.fog(), 100 ether);\n        assertEq(sai.balanceOf(this), 100 ether);\n\n        tap.bust(50 ether);\n\n        assertEq(tap.fog(),  50 ether);\n        assertEq(tap.woe(),  75 ether);\n        assertEq(sai.balanceOf(this), 75 ether);\n\n        mom.setWay(999999978020447331861593082);  // -50% / year\n        warp(1 years);\n        assertEq(wad(vox.par()), 0.5 ether);\n        // sai now worth half as much, so we cover twice as much debt\n        // for the same skr\n        tap.bust(50 ether);\n\n        assertEq(tap.fog(),   0 ether);\n        assertEq(tap.woe(),  25 ether);\n        assertEq(sai.balanceOf(this), 25 ether);\n    }\n}\n\ncontract GapTest is SaiTestBase {\n    // boom and bust have a spread parameter\n    function setUp() public {\n        super.setUp();\n\n        gem.deposit.value(500 ether)();\n        tub.join(500 ether);\n\n        sai.mint(500 ether);\n        sin.mint(500 ether);\n\n        mark(2 ether);  // 2 ref per eth => 2 sai per skr\n    }\n    function testGapSaiTapBid() public {\n        mark(1 ether);\n        mom.setTapGap(1.01 ether);  // 1% spread\n        assertEq(tap.bid(1 ether), 0.99 ether);\n        mark(2 ether);\n        assertEq(tap.bid(1 ether), 1.98 ether);\n    }\n    function testGapSaiTapAsk() public {\n        mark(1 ether);\n        mom.setTapGap(1.01 ether);  // 1% spread\n        assertEq(tap.ask(1 ether), 1.01 ether);\n        mark(2 ether);\n        assertEq(tap.ask(1 ether), 2.02 ether);\n    }\n    function testGapBoom() public {\n        sai.push(tap, 198 ether);\n        assertEq(tap.joy(), 198 ether);\n\n        mom.setTapGap(1.01 ether);  // 1% spread\n\n        var sai_before = sai.balanceOf(this);\n        var skr_before = skr.balanceOf(this);\n        tap.boom(50 ether);\n        var sai_after = sai.balanceOf(this);\n        var skr_after = skr.balanceOf(this);\n        assertEq(sai_after - sai_before, 99 ether);\n        assertEq(skr_before - skr_after, 50 ether);\n    }\n    function testGapBust() public {\n        skr.push(tap, 100 ether);\n        sin.push(tap, 200 ether);\n        assertEq(tap.fog(), 100 ether);\n        assertEq(tap.woe(), 200 ether);\n\n        mom.setTapGap(1.01 ether);\n\n        var sai_before = sai.balanceOf(this);\n        var skr_before = skr.balanceOf(this);\n        tap.bust(50 ether);\n        var sai_after = sai.balanceOf(this);\n        var skr_after = skr.balanceOf(this);\n        assertEq(skr_after - skr_before,  50 ether);\n        assertEq(sai_before - sai_after, 101 ether);\n    }\n    function testGapLimits() public {\n        uint256 legal   = 1.04 ether;\n        uint256 illegal = 1.06 ether;\n\n        var setGap = bytes4(keccak256(\"setTapGap(uint256)\"));\n\n        assertTrue(mom.call(setGap, legal));\n        assertEq(tap.gap(), legal);\n\n        assertTrue(!mom.call(setGap, illegal));\n        assertEq(tap.gap(), legal);\n    }\n\n    // join and exit have a spread parameter\n    function testGapJarBidAsk() public {\n        assertEq(tub.per(), ray(1 ether));\n        assertEq(tub.bid(1 ether), 1 ether);\n        assertEq(tub.ask(1 ether), 1 ether);\n\n        mom.setTubGap(1.01 ether);\n        assertEq(tub.bid(1 ether), 0.99 ether);\n        assertEq(tub.ask(1 ether), 1.01 ether);\n\n        assertEq(skr.balanceOf(this), 500 ether);\n        assertEq(skr.totalSupply(),   500 ether);\n        skr.burn(250 ether);\n\n        assertEq(tub.per(), ray(2 ether));\n        assertEq(tub.bid(1 ether), 1.98 ether);\n        assertEq(tub.ask(1 ether), 2.02 ether);\n    }\n    function testGapJoin() public {\n        gem.deposit.value(100 ether)();\n\n        mom.setTubGap(1.05 ether);\n        var skr_before = skr.balanceOf(this);\n        var gem_before = gem.balanceOf(this);\n        tub.join(100 ether);\n        var skr_after = skr.balanceOf(this);\n        var gem_after = gem.balanceOf(this);\n\n        assertEq(skr_after - skr_before, 100 ether);\n        assertEq(gem_before - gem_after, 105 ether);\n    }\n    function testGapExit() public {\n        gem.deposit.value(100 ether)();\n        tub.join(100 ether);\n\n        mom.setTubGap(1.05 ether);\n        var skr_before = skr.balanceOf(this);\n        var gem_before = gem.balanceOf(this);\n        tub.exit(100 ether);\n        var skr_after = skr.balanceOf(this);\n        var gem_after = gem.balanceOf(this);\n\n        assertEq(gem_after - gem_before,  95 ether);\n        assertEq(skr_before - skr_after, 100 ether);\n    }\n}\n\ncontract GasTest is SaiTestBase {\n    bytes32 cup;\n    function setUp() public {\n        super.setUp();\n\n        mark(1 ether);\n        gem.deposit.value(1000 ether)();\n\n        mom.setCap(1000 ether);\n        mom.setAxe(ray(1 ether));\n        mom.setMat(ray(1 ether));\n        mom.setTax(ray(1 ether));\n        mom.setFee(ray(1 ether));\n        mom.setTubGap(1 ether);\n        mom.setTapGap(1 ether);\n\n        cup = tub.open();\n        tub.join(1000 ether);\n        tub.lock(cup, 500 ether);\n        tub.draw(cup, 100 ether);\n    }\n    function doLock(uint256 wad) public logs_gas {\n        tub.lock(cup, wad);\n    }\n    function doFree(uint256 wad) public logs_gas {\n        tub.free(cup, wad);\n    }\n    function doDraw(uint256 wad) public logs_gas {\n        tub.draw(cup, wad);\n    }\n    function doWipe(uint256 wad) public logs_gas {\n        tub.wipe(cup, wad);\n    }\n    function doDrip() public logs_gas {\n        tub.drip();\n    }\n    function doBoom(uint256 wad) public logs_gas {\n        tap.boom(wad);\n    }\n\n    uint256 tic = 15 seconds;\n\n    function testGasLock() public {\n        warp(tic);\n        doLock(100 ether);\n        // assertTrue(false);\n    }\n    function testGasFree() public {\n        warp(tic);\n        doFree(100 ether);\n        // assertTrue(false);\n    }\n    function testGasDraw() public {\n        warp(tic);\n        doDraw(100 ether);\n        // assertTrue(false);\n    }\n    function testGasWipe() public {\n        warp(tic);\n        doWipe(100 ether);\n        // assertTrue(false);\n    }\n    function testGasBoom() public {\n        warp(tic);\n        tub.join(10 ether);\n        sai.mint(100 ether);\n        sai.push(tap, 100 ether);\n        skr.approve(tap, uint(-1));\n        doBoom(1 ether);\n        // assertTrue(false);\n    }\n    function testGasBoomHeal() public {\n        warp(tic);\n        tub.join(10 ether);\n        sai.mint(100 ether);\n        sin.mint(100 ether);\n        sai.push(tap, 100 ether);\n        sin.push(tap,  50 ether);\n        skr.approve(tap, uint(-1));\n        doBoom(1 ether);\n        // assertTrue(false);\n    }\n    function testGasDripNoop() public {\n        tub.drip();\n        doDrip();\n    }\n    function testGasDrip1s() public {\n        warp(1 seconds);\n        doDrip();\n    }\n    function testGasDrip1m() public {\n        warp(1 minutes);\n        doDrip();\n    }\n    function testGasDrip1h() public {\n        warp(1 hours);\n        doDrip();\n    }\n    function testGasDrip1d() public {\n        warp(1 days);\n        doDrip();\n    }\n}\n\ncontract FeeTest is SaiTestBase {\n    function feeSetup() public returns (bytes32 cup) {\n        mark(10 ether);\n        mark(gov, 1 ether / 2);\n        gem.deposit.value(1000 ether)();\n        gov.mint(100 ether);\n\n        mom.setCap(1000 ether);\n        mom.setFee(1000000564701133626865910626);  // 5% / day\n\n        // warp(1 days);  // make chi,rhi != 1\n\n        cup = tub.open();\n        tub.join(100 ether);\n        tub.lock(cup, 100 ether);\n        tub.draw(cup, 100 ether);\n    }\n    function testFeeSet() public {\n        assertEq(tub.fee(), ray(1 ether));\n        mom.setFee(ray(1.000000001 ether));\n        assertEq(tub.fee(), ray(1.000000001 ether));\n    }\n    function testFeeSetup() public {\n        feeSetup();\n        assertEq(tub.chi(), ray(1 ether));\n        assertEq(tub.rhi(), ray(1 ether));\n    }\n    function testFeeDrip() public {\n        feeSetup();\n        warp(1 days);\n        assertEq(tub.chi() / 10 ** 9, 1.00 ether);\n        assertEq(tub.rhi() / 10 ** 9, 1.05 ether);\n    }\n    // Unpaid fees do not accumulate as sin\n    function testFeeIce() public {\n        var cup = feeSetup();\n        assertEq(tub.din(),    100 ether);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.rap(cup),   0 ether);\n        warp(1 days);\n        assertEq(tub.din(),    100 ether);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.rap(cup),   5 ether);\n    }\n    function testFeeDraw() public {\n        var cup = feeSetup();\n        warp(1 days);\n        assertEq(tub.rap(cup),   5 ether);\n        tub.draw(cup, 100 ether);\n        assertEq(tub.rap(cup),   5 ether);\n        warp(1 days);\n        assertEq(tub.rap(cup),  15.25 ether);\n    }\n    function testFeeWipe() public {\n        var cup = feeSetup();\n        warp(1 days);\n        assertEq(tub.rap(cup),   5 ether);\n        tub.wipe(cup, 50 ether);\n        assertEq(tub.rap(cup),  2.5 ether);\n        warp(1 days);\n        assertEq(tub.rap(cup),  5.125 ether);\n    }\n    function testFeeCalcFromRap() public {\n        var cup = feeSetup();\n\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.rap(cup),   0 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.rap(cup),   5 ether);\n    }\n    function testFeeWipePays() public {\n        var cup = feeSetup();\n        warp(1 days);\n\n        assertEq(tub.rap(cup),          5 ether);\n        assertEq(gov.balanceOf(this), 100 ether);\n        tub.wipe(cup, 50 ether);\n        assertEq(tub.tab(cup),         50 ether);\n        assertEq(gov.balanceOf(this),  95 ether);\n    }\n    function testFeeWipeMoves() public {\n        var cup = feeSetup();\n        warp(1 days);\n\n        assertEq(gov.balanceOf(this), 100 ether);\n        assertEq(gov.balanceOf(pit),    0 ether);\n        tub.wipe(cup, 50 ether);\n        assertEq(gov.balanceOf(this),  95 ether);\n        assertEq(gov.balanceOf(pit),    5 ether);\n    }\n    function testFeeWipeAll() public {\n        var cup = feeSetup();\n        warp(1 days);\n\n        var wad = tub.tab(cup);\n        assertEq(wad, 100 ether);\n        var owe = tub.rap(cup);\n        assertEq(owe, 5 ether);\n\n        var ( , , art, ire) = tub.cups(cup);\n        assertEq(art, 100 ether);\n        assertEq(ire, 100 ether);\n        assertEq(rdiv(wad, tub.chi()), art);\n        assertEq(rdiv(add(wad, owe), tub.rhi()), ire);\n\n        assertEq(tub.rap(cup),   5 ether);\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(gov.balanceOf(this), 100 ether);\n        tub.wipe(cup, 100 ether);\n        assertEq(tub.rap(cup), 0 ether);\n        assertEq(tub.tab(cup), 0 ether);\n        assertEq(gov.balanceOf(this), 90 ether);\n    }\n    function testFeeWipeNoFeed() public {\n        var cup = feeSetup();\n        pep.void();\n        warp(1 days);\n\n        // fees continue to accumulate\n        assertEq(tub.rap(cup),   5 ether);\n\n        // gov is no longer taken\n        assertEq(gov.balanceOf(this), 100 ether);\n        tub.wipe(cup, 50 ether);\n        assertEq(gov.balanceOf(this), 100 ether);\n\n        // fees are still wiped proportionally\n        assertEq(tub.rap(cup),  2.5 ether);\n        warp(1 days);\n        assertEq(tub.rap(cup),  5.125 ether);\n    }\n    function testFeeWipeShut() public {\n        var cup = feeSetup();\n        warp(1 days);\n        tub.shut(cup);\n    }\n    function testFeeWipeShutEmpty() public {\n        feeSetup();\n        var cup = tub.open();\n        tub.join(100 ether);\n        tub.lock(cup, 100 ether);\n        warp(1 days);\n        tub.shut(cup);\n    }\n}\n\ncontract PitTest is SaiTestBase {\n    function testPitBurns() public {\n        gov.mint(1 ether);\n        assertEq(gov.balanceOf(pit), 0 ether);\n        gov.push(pit, 1 ether);\n\n        // mock gov authority\n        var guard = new DSGuard();\n        guard.permit(pit, gov, bytes4(keccak256('burn(uint256)')));\n        gov.setAuthority(guard);\n\n        assertEq(gov.balanceOf(pit), 1 ether);\n        pit.burn(gov);\n        assertEq(gov.balanceOf(pit), 0 ether);\n    }\n}\n\ncontract FeeTaxTest is SaiTestBase {\n    function feeSetup() public returns (bytes32 cup) {\n        mark(10 ether);\n        mark(gov, 1 ether / 2);\n        gem.deposit.value(1000 ether)();\n        gov.mint(100 ether);\n\n        mom.setCap(1000 ether);\n        mom.setFee(1000000564701133626865910626);  // 5% / day\n        mom.setTax(1000000564701133626865910626);  // 5% / day\n\n        // warp(1 days);  // make chi,rhi != 1\n\n        cup = tub.open();\n        tub.join(100 ether);\n        tub.lock(cup, 100 ether);\n        tub.draw(cup, 100 ether);\n    }\n    function testFeeTaxDrip() public {\n        feeSetup();\n        warp(1 days);\n        assertEq(tub.chi() / 10 ** 9, 1.0500 ether);\n        assertEq(tub.rhi() / 10 ** 9, 1.1025 ether);\n    }\n    // Unpaid fees do not accumulate as sin\n    function testFeeTaxIce() public {\n        var cup = feeSetup();\n\n        assertEq(tub.tab(cup), 100 ether);\n        assertEq(tub.rap(cup),   0 ether);\n\n        assertEq(tub.din(),    100 ether);\n        assertEq(tap.joy(),      0 ether);\n\n        warp(1 days);\n\n        assertEq(tub.tab(cup), 105 ether);\n        assertEq(tub.rap(cup),   5.25 ether);\n\n        assertEq(tub.din(),    105 ether);\n        assertEq(tap.joy(),      5 ether);\n    }\n    function testFeeTaxDraw() public {\n        var cup = feeSetup();\n        warp(1 days);\n        assertEq(tub.tab(cup), 105 ether);\n        tub.draw(cup, 100 ether);\n        assertEq(tub.tab(cup), 205 ether);\n    }\n    function testFeeTaxCalcFromRap() public {\n        var cup = feeSetup();\n\n        assertEq(tub.tab(cup), 100.00 ether);\n        assertEq(tub.rap(cup),   0.00 ether);\n        warp(1 days);\n        assertEq(tub.tab(cup), 105.00 ether);\n        assertEq(tub.rap(cup),   5.25 ether);\n    }\n    function testFeeTaxWipeAll() public {\n        var cup = feeSetup();\n        warp(1 days);\n\n        var wad = tub.tab(cup);\n        assertEq(wad, 105 ether);\n        var owe = tub.rap(cup);\n        assertEq(owe, 5.25 ether);\n\n        var ( , , art, ire) = tub.cups(cup);\n        assertEq(art, 100 ether);\n        assertEq(ire, 100 ether);\n        assertEq(rdiv(wad, tub.chi()), art);\n        assertEq(rdiv(add(wad, owe), tub.rhi()), ire);\n\n        sai.mint(5 ether);  // need to magic up some extra sai to pay tax\n\n        assertEq(tub.rap(cup), 5.25 ether);\n        assertEq(gov.balanceOf(this), 100 ether);\n        tub.wipe(cup, 105 ether);\n        assertEq(tub.rap(cup), 0 ether);\n        assertEq(gov.balanceOf(this), 89.5 ether);\n    }\n}\n\ncontract AxeTest is SaiTestBase {\n    function axeSetup() public returns (bytes32) {\n        mom.setCap(1000 ether);\n        mark(1 ether);\n        mom.setMat(ray(2 ether));       // require 200% collat\n        tub.join(20 ether);\n        var cup = tub.open();\n        tub.lock(cup, 20 ether);\n        tub.draw(cup, 10 ether);       // 200% collateralisation\n\n        return cup;\n    }\n    function testAxeBite1() public {\n        var cup = axeSetup();\n\n        mom.setAxe(ray(1.5 ether));\n        mom.setMat(ray(2.1 ether));\n\n        assertEq(tub.ink(cup), 20 ether);\n        tub.bite(cup);\n        assertEq(tub.ink(cup), 5 ether);\n    }\n    function testAxeBite2() public {\n        var cup = axeSetup();\n\n        mom.setAxe(ray(1.5 ether));\n        mark(0.8 ether);    // collateral value 20 -> 16\n\n        assertEq(tub.ink(cup), 20 ether);\n        tub.bite(cup);\n        assertEq(tub.ink(cup), 1.25 ether);  // (1 / 0.8)\n    }\n    function testAxeBiteParity() public {\n        var cup = axeSetup();\n\n        mom.setAxe(ray(1.5 ether));\n        mark(0.5 ether);    // collateral value 20 -> 10\n\n        assertEq(tub.ink(cup), 20 ether);\n        tub.bite(cup);\n        assertEq(tub.ink(cup), 0 ether);\n    }\n    function testAxeBiteUnder() public {\n        var cup = axeSetup();\n\n        mom.setAxe(ray(1.5 ether));\n        mark(0.4 ether);    // collateral value 20 -> 8\n\n        assertEq(tub.ink(cup), 20 ether);\n        tub.bite(cup);\n        assertEq(tub.ink(cup), 0 ether);\n    }\n    function testZeroAxeCage() public {\n        var cup = axeSetup();\n\n        mom.setAxe(ray(1 ether));\n\n        assertEq(tub.ink(cup), 20 ether);\n        top.cage();\n        tub.bite(cup);\n        tap.vent();\n        top.flow();\n        assertEq(tub.ink(cup), 10 ether);\n    }\n    function testAxeCage() public {\n        var cup = axeSetup();\n\n        mom.setAxe(ray(1.5 ether));\n\n        assertEq(tub.ink(cup), 20 ether);\n        top.cage();\n        tub.bite(cup);\n        tap.vent();\n        top.flow();\n        assertEq(tub.ink(cup), 10 ether);\n    }\n}\n\ncontract DustTest is SaiTestBase {\n    function testFailLockUnderDust() public {\n        tub.join(1 ether);\n        var cup = tub.open();\n        tub.lock(cup, 0.0049 ether);\n    }\n    function testFailFreeUnderDust() public {\n        tub.join(1 ether);\n        var cup = tub.open();\n        tub.lock(cup, 1 ether);\n        tub.free(cup, 0.995 ether);\n    }\n}\n\ncontract SymbologyTest is SaiTestBase {\n    function testSymbology() public {\n        assertEq(sai.symbol(), 'DAI');\n        assertEq(sin.symbol(), 'SIN');\n        assertEq(skr.symbol(), 'PETH');\n\n        assertEq(sai.name(), 'Dai Stablecoin v1.0');\n        assertEq(sin.name(), 'SIN');\n        assertEq(skr.name(), 'Pooled Ether');\n    }\n}\n"
  },
  {
    "path": "src/spell.t.sol",
    "content": "// (c) Nikolai Mushegian, 2017\n\n// Testing using a `DSSpell` as the `hat` in a `DSChief` for one-off\n// root calls or role changes.\n\npragma solidity ^0.4.18;\n\nimport 'ds-test/test.sol';\n\nimport 'ds-spell/spell.sol';\nimport 'ds-chief/chief.sol';\nimport 'ds-token/token.sol';\n\ncontract Target is DSThing {\n    bool public ouch;\n    function poke() public auth {\n        ouch = true;\n    }\n}\n\ncontract SpellTest is DSTest {\n    Target t;\n    DSChief c;\n    DSSpell s;\n    function setUp() public {\n        var gov = new DSToken(\"GOV\");\n        var iou = new DSToken(\"IOU\");\n        t = new Target();\n        c = new DSChief(gov, iou, 1);\n    }\n    function testRootCall() public {\n        // poke() sig: 0x18178358\n        bytes memory data = hex\"18178358\";\n        s = new DSSpell(t, 0, data);\n    }\n    // function testRoleChange() public {\n        // require(false);\n        // // setUserRole(address,uint8,bool) sig:\n        // // TODO complex packing\n    // }\n}\n"
  },
  {
    "path": "src/tap.sol",
    "content": "/// tap.sol -- liquidation engine (see also `vow`)\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) 2017  Daniel Brockman <daniel@dapphub.com>\n// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\nimport \"./tub.sol\";\n\ncontract SaiTap is DSThing {\n    DSToken  public  sai;\n    DSToken  public  sin;\n    DSToken  public  skr;\n\n    SaiVox   public  vox;\n    SaiTub   public  tub;\n\n    uint256  public  gap;  // Boom-Bust Spread\n    bool     public  off;  // Cage flag\n    uint256  public  fix;  // Cage price\n\n    // Surplus\n    function joy() public view returns (uint) {\n        return sai.balanceOf(this);\n    }\n    // Bad debt\n    function woe() public view returns (uint) {\n        return sin.balanceOf(this);\n    }\n    // Collateral pending liquidation\n    function fog() public view returns (uint) {\n        return skr.balanceOf(this);\n    }\n\n\n    function SaiTap(SaiTub tub_) public {\n        tub = tub_;\n\n        sai = tub.sai();\n        sin = tub.sin();\n        skr = tub.skr();\n\n        vox = tub.vox();\n\n        gap = WAD;\n    }\n\n    function mold(bytes32 param, uint val) public note auth {\n        if (param == 'gap') gap = val;\n    }\n\n    // Cancel debt\n    function heal() public note {\n        if (joy() == 0 || woe() == 0) return;  // optimised\n        var wad = min(joy(), woe());\n        sai.burn(wad);\n        sin.burn(wad);\n    }\n\n    // Feed price (sai per skr)\n    function s2s() public returns (uint) {\n        var tag = tub.tag();    // ref per skr\n        var par = vox.par();    // ref per sai\n        return rdiv(tag, par);  // sai per skr\n    }\n    // Boom price (sai per skr)\n    function bid(uint wad) public returns (uint) {\n        return rmul(wad, wmul(s2s(), sub(2 * WAD, gap)));\n    }\n    // Bust price (sai per skr)\n    function ask(uint wad) public returns (uint) {\n        return rmul(wad, wmul(s2s(), gap));\n    }\n    function flip(uint wad) internal {\n        require(ask(wad) > 0);\n        skr.push(msg.sender, wad);\n        sai.pull(msg.sender, ask(wad));\n        heal();\n    }\n    function flop(uint wad) internal {\n        skr.mint(sub(wad, fog()));\n        flip(wad);\n        require(joy() == 0);  // can't flop into surplus\n    }\n    function flap(uint wad) internal {\n        heal();\n        sai.push(msg.sender, bid(wad));\n        skr.burn(msg.sender, wad);\n    }\n    function bust(uint wad) public note {\n        require(!off);\n        if (wad > fog()) flop(wad);\n        else flip(wad);\n    }\n    function boom(uint wad) public note {\n        require(!off);\n        flap(wad);\n    }\n\n    //------------------------------------------------------------------\n\n    function cage(uint fix_) public note auth {\n        require(!off);\n        off = true;\n        fix = fix_;\n    }\n    function cash(uint wad) public note {\n        require(off);\n        sai.burn(msg.sender, wad);\n        require(tub.gem().transfer(msg.sender, rmul(wad, fix)));\n    }\n    function mock(uint wad) public note {\n        require(off);\n        sai.mint(msg.sender, wad);\n        require(tub.gem().transferFrom(msg.sender, this, rmul(wad, fix)));\n    }\n    function vent() public note {\n        require(off);\n        skr.burn(fog());\n    }\n}\n"
  },
  {
    "path": "src/top.sol",
    "content": "/// top.sol -- global settlement manager\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) 2017  Daniel Brockman <daniel@dapphub.com>\n// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\nimport \"./tub.sol\";\nimport \"./tap.sol\";\n\ncontract SaiTop is DSThing {\n    SaiVox   public  vox;\n    SaiTub   public  tub;\n    SaiTap   public  tap;\n\n    DSToken  public  sai;\n    DSToken  public  sin;\n    DSToken  public  skr;\n    ERC20    public  gem;\n\n    uint256  public  fix;  // sai cage price (gem per sai)\n    uint256  public  fit;  // skr cage price (ref per skr)\n    uint256  public  caged;\n    uint256  public  cooldown = 6 hours;\n\n    function SaiTop(SaiTub tub_, SaiTap tap_) public {\n        tub = tub_;\n        tap = tap_;\n\n        vox = tub.vox();\n\n        sai = tub.sai();\n        sin = tub.sin();\n        skr = tub.skr();\n        gem = tub.gem();\n    }\n\n    function era() public view returns (uint) {\n        return block.timestamp;\n    }\n\n    // force settlement of the system at a given price (sai per gem).\n    // This is nearly the equivalent of biting all cups at once.\n    // Important consideration: the gems associated with free skr can\n    // be tapped to make sai whole.\n    function cage(uint price) internal {\n        require(!tub.off() && price != 0);\n        caged = era();\n\n        tub.drip();  // collect remaining fees\n        tap.heal();  // absorb any pending fees\n\n        fit = rmul(wmul(price, vox.par()), tub.per());\n        // Most gems we can get per sai is the full balance of the tub.\n        // If there is no sai issued, we should still be able to cage.\n        if (sai.totalSupply() == 0) {\n            fix = rdiv(WAD, price);\n        } else {\n            fix = min(rdiv(WAD, price), rdiv(tub.pie(), sai.totalSupply()));\n        }\n\n        tub.cage(fit, rmul(fix, sai.totalSupply()));\n        tap.cage(fix);\n\n        tap.vent();    // burn pending sale skr\n    }\n    // cage by reading the last value from the feed for the price\n    function cage() public note auth {\n        cage(rdiv(uint(tub.pip().read()), vox.par()));\n    }\n\n    function flow() public note {\n        require(tub.off());\n        var empty = tub.din() == 0 && tap.fog() == 0;\n        var ended = era() > caged + cooldown;\n        require(empty || ended);\n        tub.flow();\n    }\n\n    function setCooldown(uint cooldown_) public auth {\n        cooldown = cooldown_;\n    }\n}\n"
  },
  {
    "path": "src/tub.sol",
    "content": "/// tub.sol -- simplified CDP engine (baby brother of `vat')\n\n// Copyright (C) 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) 2017  Daniel Brockman <daniel@dapphub.com>\n// Copyright (C) 2017  Rain Break <rainbreak@riseup.net>\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\nimport \"ds-thing/thing.sol\";\nimport \"ds-token/token.sol\";\nimport \"ds-value/value.sol\";\n\nimport \"./vox.sol\";\n\ncontract SaiTubEvents {\n    event LogNewCup(address indexed lad, bytes32 cup);\n}\n\ncontract SaiTub is DSThing, SaiTubEvents {\n    DSToken  public  sai;  // Stablecoin\n    DSToken  public  sin;  // Debt (negative sai)\n\n    DSToken  public  skr;  // Abstracted collateral\n    ERC20    public  gem;  // Underlying collateral\n\n    DSToken  public  gov;  // Governance token\n\n    SaiVox   public  vox;  // Target price feed\n    DSValue  public  pip;  // Reference price feed\n    DSValue  public  pep;  // Governance price feed\n\n    address  public  tap;  // Liquidator\n    address  public  pit;  // Governance Vault\n\n    uint256  public  axe;  // Liquidation penalty\n    uint256  public  cap;  // Debt ceiling\n    uint256  public  mat;  // Liquidation ratio\n    uint256  public  tax;  // Stability fee\n    uint256  public  fee;  // Governance fee\n    uint256  public  gap;  // Join-Exit Spread\n\n    bool     public  off;  // Cage flag\n    bool     public  out;  // Post cage exit\n\n    uint256  public  fit;  // REF per SKR (just before settlement)\n\n    uint256  public  rho;  // Time of last drip\n    uint256         _chi;  // Accumulated Tax Rates\n    uint256         _rhi;  // Accumulated Tax + Fee Rates\n    uint256  public  rum;  // Total normalised debt\n\n    uint256                   public  cupi;\n    mapping (bytes32 => Cup)  public  cups;\n\n    struct Cup {\n        address  lad;      // CDP owner\n        uint256  ink;      // Locked collateral (in SKR)\n        uint256  art;      // Outstanding normalised debt (tax only)\n        uint256  ire;      // Outstanding normalised debt\n    }\n\n    function lad(bytes32 cup) public view returns (address) {\n        return cups[cup].lad;\n    }\n    function ink(bytes32 cup) public view returns (uint) {\n        return cups[cup].ink;\n    }\n    function tab(bytes32 cup) public returns (uint) {\n        return rmul(cups[cup].art, chi());\n    }\n    function rap(bytes32 cup) public returns (uint) {\n        return sub(rmul(cups[cup].ire, rhi()), tab(cup));\n    }\n\n    // Total CDP Debt\n    function din() public returns (uint) {\n        return rmul(rum, chi());\n    }\n    // Backing collateral\n    function air() public view returns (uint) {\n        return skr.balanceOf(this);\n    }\n    // Raw collateral\n    function pie() public view returns (uint) {\n        return gem.balanceOf(this);\n    }\n\n    //------------------------------------------------------------------\n\n    function SaiTub(\n        DSToken  sai_,\n        DSToken  sin_,\n        DSToken  skr_,\n        ERC20    gem_,\n        DSToken  gov_,\n        DSValue  pip_,\n        DSValue  pep_,\n        SaiVox   vox_,\n        address  pit_\n    ) public {\n        gem = gem_;\n        skr = skr_;\n\n        sai = sai_;\n        sin = sin_;\n\n        gov = gov_;\n        pit = pit_;\n\n        pip = pip_;\n        pep = pep_;\n        vox = vox_;\n\n        axe = RAY;\n        mat = RAY;\n        tax = RAY;\n        fee = RAY;\n        gap = WAD;\n\n        _chi = RAY;\n        _rhi = RAY;\n\n        rho = era();\n    }\n\n    function era() public constant returns (uint) {\n        return block.timestamp;\n    }\n\n    //--Risk-parameter-config-------------------------------------------\n\n    function mold(bytes32 param, uint val) public note auth {\n        if      (param == 'cap') cap = val;\n        else if (param == 'mat') { require(val >= RAY); mat = val; }\n        else if (param == 'tax') { require(val >= RAY); drip(); tax = val; }\n        else if (param == 'fee') { require(val >= RAY); drip(); fee = val; }\n        else if (param == 'axe') { require(val >= RAY); axe = val; }\n        else if (param == 'gap') { require(val >= WAD); gap = val; }\n        else return;\n    }\n\n    //--Price-feed-setters----------------------------------------------\n\n    function setPip(DSValue pip_) public note auth {\n        pip = pip_;\n    }\n    function setPep(DSValue pep_) public note auth {\n        pep = pep_;\n    }\n    function setVox(SaiVox vox_) public note auth {\n        vox = vox_;\n    }\n\n    //--Tap-setter------------------------------------------------------\n    function turn(address tap_) public note {\n        require(tap  == 0);\n        require(tap_ != 0);\n        tap = tap_;\n    }\n\n    //--Collateral-wrapper----------------------------------------------\n\n    // Wrapper ratio (gem per skr)\n    function per() public view returns (uint ray) {\n        return skr.totalSupply() == 0 ? RAY : rdiv(pie(), skr.totalSupply());\n    }\n    // Join price (gem per skr)\n    function ask(uint wad) public view returns (uint) {\n        return rmul(wad, wmul(per(), gap));\n    }\n    // Exit price (gem per skr)\n    function bid(uint wad) public view returns (uint) {\n        return rmul(wad, wmul(per(), sub(2 * WAD, gap)));\n    }\n    function join(uint wad) public note {\n        require(!off);\n        require(ask(wad) > 0);\n        require(gem.transferFrom(msg.sender, this, ask(wad)));\n        skr.mint(msg.sender, wad);\n    }\n    function exit(uint wad) public note {\n        require(!off || out);\n        require(gem.transfer(msg.sender, bid(wad)));\n        skr.burn(msg.sender, wad);\n    }\n\n    //--Stability-fee-accumulation--------------------------------------\n\n    // Accumulated Rates\n    function chi() public returns (uint) {\n        drip();\n        return _chi;\n    }\n    function rhi() public returns (uint) {\n        drip();\n        return _rhi;\n    }\n    function drip() public note {\n        if (off) return;\n\n        var rho_ = era();\n        var age = rho_ - rho;\n        if (age == 0) return;    // optimised\n        rho = rho_;\n\n        var inc = RAY;\n\n        if (tax != RAY) {  // optimised\n            var _chi_ = _chi;\n            inc = rpow(tax, age);\n            _chi = rmul(_chi, inc);\n            sai.mint(tap, rmul(sub(_chi, _chi_), rum));\n        }\n\n        // optimised\n        if (fee != RAY) inc = rmul(inc, rpow(fee, age));\n        if (inc != RAY) _rhi = rmul(_rhi, inc);\n    }\n\n\n    //--CDP-risk-indicator----------------------------------------------\n\n    // Abstracted collateral price (ref per skr)\n    function tag() public view returns (uint wad) {\n        return off ? fit : wmul(per(), uint(pip.read()));\n    }\n    // Returns true if cup is well-collateralized\n    function safe(bytes32 cup) public returns (bool) {\n        var pro = rmul(tag(), ink(cup));\n        var con = rmul(vox.par(), tab(cup));\n        var min = rmul(con, mat);\n        return pro >= min;\n    }\n\n\n    //--CDP-operations--------------------------------------------------\n\n    function open() public note returns (bytes32 cup) {\n        require(!off);\n        cupi = add(cupi, 1);\n        cup = bytes32(cupi);\n        cups[cup].lad = msg.sender;\n        LogNewCup(msg.sender, cup);\n    }\n    function give(bytes32 cup, address guy) public note {\n        require(msg.sender == cups[cup].lad);\n        require(guy != 0);\n        cups[cup].lad = guy;\n    }\n\n    function lock(bytes32 cup, uint wad) public note {\n        require(!off);\n        cups[cup].ink = add(cups[cup].ink, wad);\n        skr.pull(msg.sender, wad);\n        require(cups[cup].ink == 0 || cups[cup].ink > 0.005 ether);\n    }\n    function free(bytes32 cup, uint wad) public note {\n        require(msg.sender == cups[cup].lad);\n        cups[cup].ink = sub(cups[cup].ink, wad);\n        skr.push(msg.sender, wad);\n        require(safe(cup));\n        require(cups[cup].ink == 0 || cups[cup].ink > 0.005 ether);\n    }\n\n    function draw(bytes32 cup, uint wad) public note {\n        require(!off);\n        require(msg.sender == cups[cup].lad);\n        require(rdiv(wad, chi()) > 0);\n\n        cups[cup].art = add(cups[cup].art, rdiv(wad, chi()));\n        rum = add(rum, rdiv(wad, chi()));\n\n        cups[cup].ire = add(cups[cup].ire, rdiv(wad, rhi()));\n        sai.mint(cups[cup].lad, wad);\n\n        require(safe(cup));\n        require(sai.totalSupply() <= cap);\n    }\n    function wipe(bytes32 cup, uint wad) public note {\n        require(!off);\n\n        var owe = rmul(wad, rdiv(rap(cup), tab(cup)));\n\n        cups[cup].art = sub(cups[cup].art, rdiv(wad, chi()));\n        rum = sub(rum, rdiv(wad, chi()));\n\n        cups[cup].ire = sub(cups[cup].ire, rdiv(add(wad, owe), rhi()));\n        sai.burn(msg.sender, wad);\n\n        var (val, ok) = pep.peek();\n        if (ok && val != 0) gov.move(msg.sender, pit, wdiv(owe, uint(val)));\n    }\n\n    function shut(bytes32 cup) public note {\n        require(!off);\n        require(msg.sender == cups[cup].lad);\n        if (tab(cup) != 0) wipe(cup, tab(cup));\n        if (ink(cup) != 0) free(cup, ink(cup));\n        delete cups[cup];\n    }\n\n    function bite(bytes32 cup) public note {\n        require(!safe(cup) || off);\n\n        // Take on all of the debt, except unpaid fees\n        var rue = tab(cup);\n        sin.mint(tap, rue);\n        rum = sub(rum, cups[cup].art);\n        cups[cup].art = 0;\n        cups[cup].ire = 0;\n\n        // Amount owed in SKR, including liquidation penalty\n        var owe = rdiv(rmul(rmul(rue, axe), vox.par()), tag());\n\n        if (owe > cups[cup].ink) {\n            owe = cups[cup].ink;\n        }\n\n        skr.push(tap, owe);\n        cups[cup].ink = sub(cups[cup].ink, owe);\n    }\n\n    //------------------------------------------------------------------\n\n    function cage(uint fit_, uint jam) public note auth {\n        require(!off && fit_ != 0);\n        off = true;\n        axe = RAY;\n        gap = WAD;\n        fit = fit_;         // ref per skr\n        require(gem.transfer(tap, jam));\n    }\n    function flow() public note auth {\n        require(off);\n        out = true;\n    }\n}\n"
  },
  {
    "path": "src/tub.t.sol",
    "content": "/// tub.t.sol -- Unit tests for tub.sol\n\npragma solidity ^0.4.18;\n\nimport './tub.sol';\nimport './tap.sol';\nimport 'ds-guard/guard.sol';\nimport \"ds-test/test.sol\";\n\ncontract TubTest is DSTest, DSThing {\n    address tap;\n    SaiTub  tub;\n    SaiVox  vox;\n\n    DSGuard dad;\n\n    DSValue pip;\n    DSValue pep;\n\n    DSToken sai;\n    DSToken sin;\n    DSToken skr;\n    DSToken gem;\n    DSToken gov;\n\n    function setUp() public {\n        sai = new DSToken(\"SAI\");\n        sin = new DSToken(\"SIN\");\n        skr = new DSToken(\"SKR\");\n        gem = new DSToken(\"GEM\");\n        gov = new DSToken(\"GOV\");\n        pip = new DSValue();\n        pep = new DSValue();\n        dad = new DSGuard();\n        vox = new SaiVox(RAY);\n        tub = new SaiTub(sai, sin, skr, gem, gov, pip, pep, vox, 0x123);\n        tap = 0x456;\n        tub.turn(tap);\n\n        //Set whitelist authority\n        skr.setAuthority(dad);\n\n        //Permit tub to 'mint' and 'burn' SKR\n        dad.permit(tub, skr, bytes4(keccak256('mint(address,uint256)')));\n        dad.permit(tub, skr, bytes4(keccak256('burn(address,uint256)')));\n\n        //Allow tub to mint, burn, and transfer gem/skr without approval\n        gem.approve(tub);\n        skr.approve(tub);\n        sai.approve(tub);\n\n        gem.mint(6 ether);\n\n        //Verify initial token balances\n        assertEq(gem.balanceOf(this), 6 ether);\n        assertEq(gem.balanceOf(tub), 0 ether);\n        assertEq(skr.totalSupply(), 0 ether);\n\n        assert(!tub.off());\n    }\n\n    function testFailTurnAgain() public {\n        tub.turn(0x789);\n    }\n\n    function testPie() public {\n        assertEq(tub.pie(), gem.balanceOf(tub));\n        assertEq(tub.pie(), 0 ether);\n        gem.mint(75 ether);\n        tub.join(72 ether);\n        assertEq(tub.pie(), gem.balanceOf(tub));\n        assertEq(tub.pie(), 72 ether);\n    }\n\n    function testPer() public {\n        tub.join(5 ether);\n        assertEq(skr.totalSupply(), 5 ether);\n        assertEq(tub.per(), rdiv(5 ether, 5 ether));\n    }\n\n    function testTag() public {\n        tub.pip().poke(bytes32(1 ether));\n        assertEq(tub.pip().read(), bytes32(1 ether));\n        assertEq(wmul(tub.per(), uint(tub.pip().read())), tub.tag());\n        tub.pip().poke(bytes32(5 ether));\n        assertEq(tub.pip().read(), bytes32(5 ether));\n        assertEq(wmul(tub.per(), uint(tub.pip().read())), tub.tag());\n    }\n\n    function testGap() public {\n        assertEq(tub.gap(), WAD);\n        tub.mold('gap', 2 ether);\n        assertEq(tub.gap(), 2 ether);\n        tub.mold('gap', wmul(WAD, 10 ether));\n        assertEq(tub.gap(), wmul(WAD, 10 ether));\n    }\n\n    function testAsk() public {\n        assertEq(tub.per(), RAY);\n        assertEq(tub.ask(3 ether), rmul(3 ether, wmul(RAY, tub.gap())));\n        assertEq(tub.ask(wmul(WAD, 33)), rmul(wmul(WAD, 33), wmul(RAY, tub.gap())));\n    }\n\n    function testBid() public {\n        assertEq(tub.per(), RAY);\n        assertEq(tub.bid(4 ether), rmul(4 ether, wmul(tub.per(), sub(2 * WAD, tub.gap()))));\n        assertEq(tub.bid(wmul(5 ether,3333333)), rmul(wmul(5 ether,3333333), wmul(tub.per(), sub(2 * WAD, tub.gap()))));\n    }\n\n    function testJoin() public {\n        tub.join(3 ether);\n        assertEq(gem.balanceOf(this), 3 ether);\n        assertEq(gem.balanceOf(tub), 3 ether);\n        assertEq(skr.totalSupply(), 3 ether);\n        tub.join(1 ether);\n        assertEq(gem.balanceOf(this), 2 ether);\n        assertEq(gem.balanceOf(tub), 4 ether);\n        assertEq(skr.totalSupply(), 4 ether);\n    }\n\n    function testExit() public {\n        gem.mint(10 ether);\n        assertEq(gem.balanceOf(this), 16 ether);\n\n        tub.join(12 ether);\n        assertEq(gem.balanceOf(tub), 12 ether);\n        assertEq(gem.balanceOf(this), 4 ether);\n        assertEq(skr.totalSupply(), 12 ether);\n\n        tub.exit(3 ether);\n        assertEq(gem.balanceOf(tub), 9 ether);\n        assertEq(gem.balanceOf(this), 7 ether);\n        assertEq(skr.totalSupply(), 9 ether);\n\n        tub.exit(7 ether);\n        assertEq(gem.balanceOf(tub), 2 ether);\n        assertEq(gem.balanceOf(this), 14 ether);\n        assertEq(skr.totalSupply(), 2 ether);\n    }\n\n    function testCage() public {\n        tub.join(5 ether);\n        assertEq(gem.balanceOf(tub), 5 ether);\n        assertEq(gem.balanceOf(this), 1 ether);\n        assertEq(skr.totalSupply(), 5 ether);\n        assert(!tub.off());\n\n        tub.cage(tub.per(), 5 ether);\n        assertEq(gem.balanceOf(tub), 0 ether);\n        assertEq(gem.balanceOf(tap), 5 ether);\n        assertEq(skr.totalSupply(), 5 ether);\n        assert(tub.off());\n    }\n\n    function testFlow() public {\n        tub.join(1 ether);\n        tub.cage(tub.per(), 1 ether);\n        assert(tub.off());\n        assert(!tub.out());\n        tub.flow();\n        assert(tub.out());\n    }\n}\n"
  },
  {
    "path": "src/vox.sol",
    "content": "/// vox.sol -- target price feed\n\n// Copyright (C) 2016, 2017  Nikolai Mushegian <nikolai@dapphub.com>\n// Copyright (C) 2016, 2017  Daniel Brockman <daniel@dapphub.com>\n// Copyright (C) 2017        Rain Break <rainbreak@riseup.net>\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\nimport \"ds-thing/thing.sol\";\n\ncontract SaiVox is DSThing {\n    uint256  _par;\n    uint256  _way;\n\n    uint256  public  fix;\n    uint256  public  how;\n    uint256  public  tau;\n\n    function SaiVox(uint par_) public {\n        _par = fix = par_;\n        _way = RAY;\n        tau  = era();\n    }\n\n    function era() public view returns (uint) {\n        return block.timestamp;\n    }\n\n    function mold(bytes32 param, uint val) public note auth {\n        if (param == 'way') _way = val;\n    }\n\n    // Dai Target Price (ref per dai)\n    function par() public returns (uint) {\n        prod();\n        return _par;\n    }\n    function way() public returns (uint) {\n        prod();\n        return _way;\n    }\n\n    function tell(uint256 ray) public note auth {\n        fix = ray;\n    }\n    function tune(uint256 ray) public note auth {\n        how = ray;\n    }\n\n    function prod() public note {\n        var age = era() - tau;\n        if (age == 0) return;  // optimised\n        tau = era();\n\n        if (_way != RAY) _par = rmul(_par, rpow(_way, age));  // optimised\n\n        if (how == 0) return;  // optimised\n        var wag = int128(how * age);\n        _way = inj(prj(_way) + (fix < _par ? wag : -wag));\n    }\n\n    function inj(int128 x) internal pure returns (uint256) {\n        return x >= 0 ? uint256(x) + RAY\n            : rdiv(RAY, RAY + uint256(-x));\n    }\n    function prj(uint256 x) internal pure returns (int128) {\n        return x >= RAY ? int128(x - RAY)\n            : int128(RAY) - int128(rdiv(RAY, x));\n    }\n}\n"
  },
  {
    "path": "src/vox.t.sol",
    "content": "pragma solidity ^0.4.18;\n\nimport \"ds-test/test.sol\";\nimport \"ds-math/math.sol\";\nimport './vox.sol';\n\ncontract TestWarp is DSNote {\n    uint  _era;\n\n    function TestWarp() public {\n        _era = uint(now);\n    }\n\n    function era() public view returns (uint) {\n        return _era == 0 ? now : _era;\n    }\n\n    function warp(uint age) public note {\n        require(_era != 0);\n        _era = age == 0 ? 0 : _era + age;\n    }\n}\n\ncontract DevVox is SaiVox, TestWarp {\n    function DevVox(uint par_) SaiVox(par_) public {}\n}\n\ncontract VoxTest is DSTest, DSMath {\n    DevVox vox;\n\n    function wad(uint256 ray_) internal pure returns (uint256) {\n        return wdiv(ray_, RAY);\n    }\n\n    function setUp() public {\n        vox = new DevVox(RAY);\n    }\n    function testVoxDefaultPar() public {\n        assertEq(vox.par(), RAY);\n    }\n    function testVoxDefaultWay() public {\n        assertEq(vox.way(), RAY);\n    }\n    function testVoxCoax() public {\n        vox.mold('way', 999999406327787478619865402);  // -5% / day\n        assertEq(vox.way(), 999999406327787478619865402);\n    }\n    function testVoxProd() public {\n        vox.mold('way', 999999406327787478619865402);  // -5% / day\n        vox.prod();\n    }\n    function testVoxProdAfterWarp1day() public {\n        vox.mold('way', 999999406327787478619865402);  // -5% / day\n        vox.warp(1 days);\n        vox.prod();\n    }\n    function testVoxParAfterWarp1day() public {\n        vox.mold('way', 999999406327787478619865402);  // -5% / day\n        vox.warp(1 days);\n        assertEq(wad(vox.par()), 0.95 ether);\n    }\n    function testVoxProdAfterWarp2day() public {\n        vox.mold('way', 999991977495368425989823173);  // -50% / day\n        vox.warp(2 days);\n        assertEq(wad(vox.par()), 0.25 ether);\n    }\n}\n\ncontract VoxHowTest is DSTest, DSMath {\n    DevVox vox;\n\n    function ray(uint256 wad_) internal pure returns (uint256) {\n        return wad_ * 10 ** 9;\n    }\n    function setUp() public {\n        vox = new DevVox(ray(0.75 ether));\n        vox.tune(ray(0.002 ether));\n    }\n    function test_price_too_low() public {\n        vox.tell(ray(0.70 ether));\n        vox.warp(1 seconds);\n        assertEq(vox.way(), ray(1.002 ether));\n        vox.warp(2 seconds);\n        assertEq(vox.way(), ray(1.006 ether));\n    }\n\n    function test_price_too_high() public {\n        vox.tell(ray(0.80 ether));\n        vox.warp(1 seconds);\n        assertEq(vox.way(), 998003992015968063872255489);\n        vox.warp(2 seconds);\n        assertEq(vox.way(), 994035785288270377733598410);\n    }\n}\n"
  },
  {
    "path": "src/weth9.sol",
    "content": "// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity ^0.4.18;\n\ncontract WETH9 {\n    string public name     = \"Wrapped Ether\";\n    string public symbol   = \"WETH\";\n    uint8  public decimals = 18;\n\n    event  Approval(address indexed src, address indexed guy, uint wad);\n    event  Transfer(address indexed src, address indexed dst, uint wad);\n    event  Deposit(address indexed dst, uint wad);\n    event  Withdrawal(address indexed src, uint wad);\n\n    mapping (address => uint)                       public  balanceOf;\n    mapping (address => mapping (address => uint))  public  allowance;\n\n    function() public payable {\n        deposit();\n    }\n    function deposit() public payable {\n        balanceOf[msg.sender] += msg.value;\n        Deposit(msg.sender, msg.value);\n    }\n    function withdraw(uint wad) public {\n        require(balanceOf[msg.sender] >= wad);\n        balanceOf[msg.sender] -= wad;\n        msg.sender.transfer(wad);\n        Withdrawal(msg.sender, wad);\n    }\n\n    function totalSupply() public view returns (uint) {\n        return this.balance;\n    }\n\n    function approve(address guy, uint wad) public returns (bool) {\n        allowance[msg.sender][guy] = wad;\n        Approval(msg.sender, guy, wad);\n        return true;\n    }\n\n    function transfer(address dst, uint wad) public returns (bool) {\n        return transferFrom(msg.sender, dst, wad);\n    }\n\n    function transferFrom(address src, address dst, uint wad)\n        public\n        returns (bool)\n    {\n        require(balanceOf[src] >= wad);\n\n        if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {\n            require(allowance[src][msg.sender] >= wad);\n            allowance[src][msg.sender] -= wad;\n        }\n\n        balanceOf[src] -= wad;\n        balanceOf[dst] += wad;\n\n        Transfer(src, dst, wad);\n\n        return true;\n    }\n}\n\n\n/*\n                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\n*/\n"
  }
]