Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
balasan committed Mar 20, 2018
0 parents commit 0fd82f5
Show file tree
Hide file tree
Showing 29 changed files with 10,213 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
@@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-2", "stage-3"]
}
5 changes: 5 additions & 0 deletions .env.example
@@ -0,0 +1,5 @@
# configure your infura api key (not technically required)
INFURA_API_KEY=

# change the mnemonic that your hd wallet is seeded with
MNEMONIC=
9 changes: 9 additions & 0 deletions .eslintignore
@@ -0,0 +1,9 @@
# Dependency directory
node_modules

/migrations

truffle-config.js

coverage
coverage.json
34 changes: 34 additions & 0 deletions .eslintrc.js
@@ -0,0 +1,34 @@
module.exports = {
"extends": "airbnb-base",
"plugins": [
"import"
],
"rules": {
"no-underscore-dangle": 0,
"comma-dangle": ["error", "only-multiline"],
"prefer-const": "off",
"no-plusplus": "off",
"no-param-reassign": 0,
"no-return-assign": 0,
"global-require": 0,
"arrow-parens": 0,
"prefer-template": 0,
"no-nested-ternary": 0,
"no-mixed-operators": 0,
"no-confusing-arrow": 0,
"prefer-arrow-callback": 0,
"prefer-arrow-callback": 0,
"func-names": 0,
"prefer-destructuring": 1
},
"env": {
"browser": true,
"mocha": true,
},
"globals" : {
"artifacts": false,
"contract": false,
"assert": false,
"web3": false
},
};
39 changes: 39 additions & 0 deletions .gitignore
@@ -0,0 +1,39 @@
# Dependency directory
node_modules

# Debug log from npm
npm-debug.log

# local env variables
.env

# truffle build directory
build/

# lol macs
.DS_Store

# scratchpad
scratchpad

*.swp
*.swo

# Logs
logs
*.log

# Runtime data
pids
*.pid
*.seed
allFiredEvents
scTopics

# Coverage directory used by tools like istanbul
coverage
coverage.json
coverageEnv

# node-waf configuration
.lock-wscript
14 changes: 14 additions & 0 deletions .solcover.js
@@ -0,0 +1,14 @@
module.exports = {
// port: 6545,
// testrpcOptions: '-p 6545 -u 0x54fd80d6ae7584d8e9a19fe1df43f04e5282cc43',
// testCommand: 'mocha --timeout 5000',
// norpc: true,
// dir: './secretDirectory',
copyPackages: ['zeppelin-solidity'],
skipFiles: [
// 'BancorFormula.sol',
'ConvertLib.sol',
'mocks',
'interfaces'
]
};
1 change: 1 addition & 0 deletions .soliumignore
@@ -0,0 +1 @@
node_modules
16 changes: 16 additions & 0 deletions .soliumrc.json
@@ -0,0 +1,16 @@
{
"extends": "solium:recommended",
"plugins": [
"security"
],
"rules": {
"quotes": [
"error",
"double"
],
"indentation": [
"error",
2
]
}
}
105 changes: 105 additions & 0 deletions CONTRIBUTING.md
@@ -0,0 +1,105 @@
Contributing (Based on Zeppelin Contribution Guidelines)
=======

## Design Guidelines

These are some global design goals based on Open-Zeppelin design.

### D0 - Security in Depth
We strive to provide secure, tested, audited code. To achieve this, we need to match intention with function. Thus, documentation, code clarity, community review and security discussions are fundamental.

### D1 - Simple and Modular
Simpler code means easier audits, and better understanding of what each component does. We look for small files, small contracts, and small functions. If you can separate a contract into two independent functionalities you should probably do it.

### D2 - Naming Matters

We take our time with picking names. Code is going to be written once, and read hundreds of times. Renaming for clarity is encouraged.

### D3 - Tests

Write tests for all your code. We encourage Test Driven Development so we know when our code is right. Even though not all code in the repository is tested at the moment, we aim to test every line of code in the future.

### D4 - Check preconditions and post-conditions

A very important way to prevent vulnerabilities is to catch a contract’s inconsistent state as early as possible. This is why we want functions to check pre- and post-conditions for executing its logic. When writing code, ask yourself what you are expecting to be true before and after the function runs, and express it in code.

### D5 - Code Consistency

Consistency on the way classes are used is paramount to an easier understanding of the library. The codebase should be as unified as possible. Read existing code and get inspired before you write your own. Follow the style guidelines. Don’t hesitate to ask for help on how to best write a specific piece of code.

### D6 - Regular Audits
Following good programming practices is a way to reduce the risk of vulnerabilities, but professional code audits are still needed. We will perform regular code audits on major releases, and hire security professionals to provide independent review.

## Style Guidelines

The design guidelines have quite a high abstraction level. These style guidelines are more concrete and easier to apply, and also more opinionated.

### General

#### G0 - Default to Solidity's official style guide.

Follow the official Solidity style guide: https://solidity.readthedocs.io/en/latest/style-guide.html

#### G1 - No Magic Constants

Avoid constants in the code as much as possible. Magic strings are also magic constants.

#### G2 - Code that Fails Early

We ask our code to fail as soon as possible when an unexpected input was provided or unexpected state was found.

#### G3 - Internal Amounts Must be Signed Integers and Represent the Smallest Units.

Avoid representation errors by always dealing with weis when handling ether. GUIs can convert to more human-friendly representations. Use Signed Integers (int) to prevent underflow problems.


### Testing

#### T1 - Tests Must be Written Elegantly

Style guidelines are not relaxed for tests. Tests are a good way to show how to use the library, and maintaining them is extremely necessary.

Don't write long tests, write helper functions to make them be as short and concise as possible (they should take just a few lines each), and use good variable names.

#### T2 - Tests Must not be Random

Inputs for tests should not be generated randomly. Accounts used to create test contracts are an exception, those can be random. Also, the type and structure of outputs should be checked.


### Documentation

TODO

## Pull Request Workflow

Our workflow is based on GitHub's pull requests. We use feature branches, prepended with: `test`, `feature`, `fix`, `refactor`, or `remove` according to the change the branch introduces. Some examples for such branches are:
```sh
git checkout -b test/some-module
git checkout -b feature/some-new-stuff
git checkout -b fix/some-bug
git checkout -b remove/some-file
```

We expect pull requests to be rebased to the master branch before merging:
```sh
git remote add upstream git@github.com:relevant-community/bonding-curve.git
git pull --rebase upstream master
```

Note that we require rebasing your branch instead of merging it, for commit readability reasons.

After that, you can push the changes to your fork, by doing:
```sh
git push origin your_branch_name
git push origin feature/some-new-stuff
git push origin fix/some-bug
```

Finally go to [github.com/relevant-community/bonding-curve](https://github.com/relevant-community/bonding-curve) in your web browser and issue a new pull request.

Main contributors will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of the library.

If you have any questions feel free to post them to
[github.com/relevant-community/bonding-curve/issues](https://github.com/relevant-community/bonding-curve/issues).

Thanks for your time and code!
28 changes: 28 additions & 0 deletions README.md
@@ -0,0 +1,28 @@
# Bonding Curve aka Automatic Market Maker Contract
The code is based on Bancor Contracts: https://github.com/bancorprotocol/contracts

### Install
```
npm install
```
### Test
```
npm test
```
### Run Tests Continuously
```
npm watch
```

## Contributing
If you would like to contribute, check out the [contribution guidelines](https://github.com/relevant-community/bonding-curve/CONTRIBUTING.md)

## Resources
Some background reading about bonding curves:
https://hackernoon.com/how-to-make-bonding-curves-for-continuous-token-models-3784653f8b17
https://medium.com/@simondlr/tokens-2-0-curved-token-bonding-in-curation-markets-1764a2e0bee5
and Bancor formula:
https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view



91 changes: 91 additions & 0 deletions contracts/BancorFormula.sol
@@ -0,0 +1,91 @@
pragma solidity ^0.4.18;
import "./Power.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";

/**
* Bancor formula by Bancor
* https://github.com/bancorprotocol/contracts
* Modified from the original by Slava Balasanov
* Split Power.sol out from BancorFormula.sol and replace SafeMath formulas with zeppelin's SafeMath
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
* and to You under the Apache License, Version 2.0. "
*/
contract BancorFormula is Power {
using SafeMath for uint256;

string public version = "0.3";
uint32 private constant MAX_WEIGHT = 1000000;

/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public constant returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);

// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;

// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _supply.mul(_depositAmount).div(_connectorBalance);

uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}

/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public constant returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);

// special case for 0 sell amount
if (_sellAmount == 0)
return 0;

// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;

// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _connectorBalance.mul(_sellAmount).div(_supply);

uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = _connectorBalance.mul(result);
uint256 temp2 = _connectorBalance << precision;
return temp1.sub(temp2).div(result);
}
}

0 comments on commit 0fd82f5

Please sign in to comment.