mirror of
https://github.com/oceanprotocol-archive/squid-js.git
synced 2024-02-02 15:31:51 +01:00
commit
2d0f6d23f2
18
.babelrc
Normal file
18
.babelrc
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"presets": [
|
||||
"es2015",
|
||||
[
|
||||
"env", { "useBuiltIns": true }
|
||||
],
|
||||
"stage-2"
|
||||
],
|
||||
"plugins": [
|
||||
[
|
||||
"transform-runtime",
|
||||
{
|
||||
"polyfill": false,
|
||||
"regenerator": true
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
3
.eslintrc
Normal file
3
.eslintrc
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": ["oceanprotocol", "oceanprotocol/react"]
|
||||
}
|
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
node_modules/
|
25
.travis.yml
Normal file
25
.travis.yml
Normal file
@ -0,0 +1,25 @@
|
||||
dist: trusty
|
||||
sudo: required
|
||||
group: beta
|
||||
language: node_js
|
||||
node_js:
|
||||
- "8"
|
||||
|
||||
services:
|
||||
- docker
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- node_modules
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
|
||||
before_install:
|
||||
- npm install -g npm
|
||||
|
||||
script:
|
||||
- npm run build
|
||||
|
||||
notifications:
|
||||
email: false
|
50
README.md
50
README.md
@ -1,2 +1,48 @@
|
||||
# ocean-client-js
|
||||
Ocean Javascript Client
|
||||
[![banner](https://raw.githubusercontent.com/oceanprotocol/art/master/github/repo-banner%402x.png)](https://oceanprotocol.com)
|
||||
|
||||
# keeper-js
|
||||
|
||||
> 🐋 JavaScript implementation of ocean protocol keeper
|
||||
> [oceanprotocol.com](https://oceanprotocol.com)
|
||||
|
||||
[![Travis (.com)](https://img.shields.io/travis/com/oceanprotocol/ocean-client-js.svg)](https://travis-ci.com/oceanprotocol/ocean-client-js)
|
||||
[![GitHub contributors](https://img.shields.io/github/contributors/oceanprotocol/ocean-client-js.svg)](https://github.com/oceanprotocol/ocean-client-js/graphs/contributors)
|
||||
|
||||
---
|
||||
|
||||
**🐲🦑 THERE BE DRAGONS AND SQUIDS. This is in alpha state and you can expect running into problems. If you run into them, please open up [a new issue](https://github.com/oceanprotocol/ocean-client-js/issues). 🦑🐲**
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Get Started](#get-started)
|
||||
- [License](#license)
|
||||
|
||||
---
|
||||
|
||||
## Get Started
|
||||
To start develppment you need to:
|
||||
```batch
|
||||
npm i
|
||||
npm run start:dev
|
||||
```
|
||||
|
||||
This will start a watcher for changes of the code.
|
||||
|
||||
## License
|
||||
|
||||
```
|
||||
Copyright 2018 Ocean Protocol Foundation Ltd.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
81
dist/contractLoader.js
vendored
Normal file
81
dist/contractLoader.js
vendored
Normal file
@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _regenerator = require('babel-runtime/regenerator');
|
||||
|
||||
var _regenerator2 = _interopRequireDefault(_regenerator);
|
||||
|
||||
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
|
||||
|
||||
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
|
||||
|
||||
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
|
||||
|
||||
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
|
||||
|
||||
var _createClass2 = require('babel-runtime/helpers/createClass');
|
||||
|
||||
var _createClass3 = _interopRequireDefault(_createClass2);
|
||||
|
||||
var _truffleContract = require('truffle-contract');
|
||||
|
||||
var _truffleContract2 = _interopRequireDefault(_truffleContract);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var contracts = [];
|
||||
|
||||
var ContractLoader = function () {
|
||||
function ContractLoader() {
|
||||
(0, _classCallCheck3.default)(this, ContractLoader);
|
||||
}
|
||||
|
||||
(0, _createClass3.default)(ContractLoader, null, [{
|
||||
key: '_doLoad',
|
||||
value: function () {
|
||||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(what, where, provider) {
|
||||
var artifact, contract;
|
||||
return _regenerator2.default.wrap(function _callee$(_context) {
|
||||
while (1) {
|
||||
switch (_context.prev = _context.next) {
|
||||
case 0:
|
||||
// console.log("Loading", what, "from", where)
|
||||
/* eslint-disable-next-line */
|
||||
artifact = require('@oceanprotocol/keeper-contracts/artifacts/' + what + '.' + where);
|
||||
contract = (0, _truffleContract2.default)(artifact);
|
||||
|
||||
contract.setProvider(provider);
|
||||
_context.next = 5;
|
||||
return contract.at(artifact.address);
|
||||
|
||||
case 5:
|
||||
contracts[what] = _context.sent;
|
||||
return _context.abrupt('return', contracts[what]);
|
||||
|
||||
case 7:
|
||||
case 'end':
|
||||
return _context.stop();
|
||||
}
|
||||
}
|
||||
}, _callee, this);
|
||||
}));
|
||||
|
||||
function _doLoad(_x, _x2, _x3) {
|
||||
return _ref.apply(this, arguments);
|
||||
}
|
||||
|
||||
return _doLoad;
|
||||
}()
|
||||
}, {
|
||||
key: 'load',
|
||||
value: function load(what, where, provider) {
|
||||
return contracts[what] || ContractLoader._doLoad(what, where, provider);
|
||||
}
|
||||
}]);
|
||||
return ContractLoader;
|
||||
}();
|
||||
|
||||
exports.default = ContractLoader;
|
60
dist/ocean-agent.js
vendored
Normal file
60
dist/ocean-agent.js
vendored
Normal file
@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
|
||||
|
||||
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
|
||||
|
||||
var _createClass2 = require('babel-runtime/helpers/createClass');
|
||||
|
||||
var _createClass3 = _interopRequireDefault(_createClass2);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/* global fetch */
|
||||
|
||||
var OceanAgent = function () {
|
||||
function OceanAgent(connectionUrl) {
|
||||
(0, _classCallCheck3.default)(this, OceanAgent);
|
||||
|
||||
this.assetsUrl = connectionUrl + '/assets';
|
||||
}
|
||||
|
||||
(0, _createClass3.default)(OceanAgent, [{
|
||||
key: 'getAssetsMetadata',
|
||||
value: function getAssetsMetadata() {
|
||||
return fetch(this.assetsUrl + '/metadata', { method: 'GET' }).then(function (res) {
|
||||
return res.json();
|
||||
}).then(function (data) {
|
||||
return JSON.parse(data);
|
||||
});
|
||||
}
|
||||
}, {
|
||||
key: 'publishDataAsset',
|
||||
value: function publishDataAsset(asset) {
|
||||
return fetch(this.assetsUrl + '/metadata', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(asset),
|
||||
headers: { 'Content-type': 'application/json' }
|
||||
}).then(function (response) {
|
||||
console.log('Success:', response);
|
||||
if (response.ok) {
|
||||
console.log('Success:', response);
|
||||
return true;
|
||||
}
|
||||
console.log('Failed: ', response.status, response.statusText);
|
||||
return false;
|
||||
// throw new Error(response.statusText ? response.statusText : `publish asset failed with status ${response.status}`)
|
||||
}).catch(function (error) {
|
||||
console.log('Publish asset to ocean database could not be completed: ' + error.message());
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}]);
|
||||
return OceanAgent;
|
||||
}();
|
||||
|
||||
exports.default = OceanAgent;
|
383
dist/ocean-keeper.js
vendored
Normal file
383
dist/ocean-keeper.js
vendored
Normal file
@ -0,0 +1,383 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _extends2 = require('babel-runtime/helpers/extends');
|
||||
|
||||
var _extends3 = _interopRequireDefault(_extends2);
|
||||
|
||||
var _regenerator = require('babel-runtime/regenerator');
|
||||
|
||||
var _regenerator2 = _interopRequireDefault(_regenerator);
|
||||
|
||||
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');
|
||||
|
||||
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
|
||||
|
||||
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
|
||||
|
||||
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
|
||||
|
||||
var _createClass2 = require('babel-runtime/helpers/createClass');
|
||||
|
||||
var _createClass3 = _interopRequireDefault(_createClass2);
|
||||
|
||||
var _web = require('web3');
|
||||
|
||||
var _web2 = _interopRequireDefault(_web);
|
||||
|
||||
var _contractLoader = require('./contractLoader');
|
||||
|
||||
var _contractLoader2 = _interopRequireDefault(_contractLoader);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var DEFAULT_GAS = 300000;
|
||||
|
||||
var OceanKeeper = function () {
|
||||
function OceanKeeper(uri, network) {
|
||||
(0, _classCallCheck3.default)(this, OceanKeeper);
|
||||
|
||||
var web3Provider = new _web2.default.providers.HttpProvider(uri);
|
||||
this.web3 = new _web2.default(web3Provider);
|
||||
this.defaultGas = DEFAULT_GAS;
|
||||
this.network = network || 'development';
|
||||
}
|
||||
|
||||
(0, _createClass3.default)(OceanKeeper, [{
|
||||
key: 'initContracts',
|
||||
value: function () {
|
||||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
|
||||
return _regenerator2.default.wrap(function _callee$(_context) {
|
||||
while (1) {
|
||||
switch (_context.prev = _context.next) {
|
||||
case 0:
|
||||
_context.next = 2;
|
||||
return _contractLoader2.default.load('OceanToken', this.network, this.web3.currentProvider);
|
||||
|
||||
case 2:
|
||||
this.oceanToken = _context.sent;
|
||||
_context.next = 5;
|
||||
return _contractLoader2.default.load('OceanMarket', this.network, this.web3.currentProvider);
|
||||
|
||||
case 5:
|
||||
this.oceanMarket = _context.sent;
|
||||
_context.next = 8;
|
||||
return _contractLoader2.default.load('OceanAuth', this.network, this.web3.currentProvider);
|
||||
|
||||
case 8:
|
||||
this.oceanAuth = _context.sent;
|
||||
return _context.abrupt('return', {
|
||||
oceanToken: this.oceanToken,
|
||||
oceanMarket: this.oceanMarket,
|
||||
oceanAuth: this.oceanAuth
|
||||
});
|
||||
|
||||
case 10:
|
||||
case 'end':
|
||||
return _context.stop();
|
||||
}
|
||||
}
|
||||
}, _callee, this);
|
||||
}));
|
||||
|
||||
function initContracts() {
|
||||
return _ref.apply(this, arguments);
|
||||
}
|
||||
|
||||
return initContracts;
|
||||
}()
|
||||
|
||||
// web3 wrappers
|
||||
|
||||
}, {
|
||||
key: 'sign',
|
||||
value: function sign(accountAddress, message) {
|
||||
return this.web3.eth.sign(accountAddress, message);
|
||||
}
|
||||
}, {
|
||||
key: 'getMessageHash',
|
||||
value: function getMessageHash(message) {
|
||||
return this.web3.sha3('\x19Ethereum Signed Message:\n' + message.length + message);
|
||||
}
|
||||
|
||||
// call functions (costs no gas)
|
||||
|
||||
}, {
|
||||
key: 'checkAsset',
|
||||
value: function checkAsset(assetId) {
|
||||
return this.oceanMarket.checkAsset(assetId);
|
||||
}
|
||||
}, {
|
||||
key: 'getBalance',
|
||||
value: function getBalance(accountAddress) {
|
||||
return this.oceanToken.balanceOf.call(accountAddress);
|
||||
}
|
||||
}, {
|
||||
key: 'getAssetPrice',
|
||||
value: function getAssetPrice(assetId) {
|
||||
return this.oceanMarket.getAssetPrice(assetId).then(function (price) {
|
||||
return price.toNumber();
|
||||
});
|
||||
}
|
||||
}, {
|
||||
key: 'getOrderStatus',
|
||||
value: function getOrderStatus(orderId) {
|
||||
return this.oceanAuth.statusOfAccessRequest(orderId);
|
||||
}
|
||||
}, {
|
||||
key: 'verifyOrderPayment',
|
||||
value: function verifyOrderPayment(orderId) {
|
||||
return this.oceanMarket.verifyPaymentReceived(orderId);
|
||||
}
|
||||
}, {
|
||||
key: 'getEncryptedAccessToken',
|
||||
value: function getEncryptedAccessToken(orderId, senderAddress) {
|
||||
return this.oceanAuth.getEncryptedAccessToken(orderId, { from: senderAddress });
|
||||
}
|
||||
}, {
|
||||
key: 'getConsumerOrders',
|
||||
value: function () {
|
||||
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(consumerAddress) {
|
||||
var _this = this;
|
||||
|
||||
var accessConsentEvent, _resolve, _reject, promise, getEvents, events, orders;
|
||||
|
||||
return _regenerator2.default.wrap(function _callee3$(_context3) {
|
||||
while (1) {
|
||||
switch (_context3.prev = _context3.next) {
|
||||
case 0:
|
||||
accessConsentEvent = this.oceanAuth.AccessConsentRequested({ _consumer: consumerAddress }, {
|
||||
fromBlock: 0,
|
||||
toBlock: 'latest'
|
||||
});
|
||||
_resolve = null;
|
||||
_reject = null;
|
||||
promise = new Promise(function (resolve, reject) {
|
||||
_resolve = resolve;
|
||||
_reject = reject;
|
||||
});
|
||||
|
||||
getEvents = function getEvents() {
|
||||
accessConsentEvent.get(function (error, logs) {
|
||||
if (error) {
|
||||
_reject(error);
|
||||
throw new Error(error);
|
||||
} else {
|
||||
_resolve(logs);
|
||||
}
|
||||
});
|
||||
return promise;
|
||||
};
|
||||
|
||||
_context3.next = 7;
|
||||
return getEvents().then(function (events) {
|
||||
return events;
|
||||
});
|
||||
|
||||
case 7:
|
||||
events = _context3.sent;
|
||||
|
||||
// let orders = await this.buildOrdersFromEvents(events, consumerAddress).then((result) => result)
|
||||
orders = events.filter(function (obj) {
|
||||
return obj.args._consumer === consumerAddress;
|
||||
}).map(function () {
|
||||
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(event) {
|
||||
return _regenerator2.default.wrap(function _callee2$(_context2) {
|
||||
while (1) {
|
||||
switch (_context2.prev = _context2.next) {
|
||||
case 0:
|
||||
_context2.t0 = _extends3.default;
|
||||
_context2.t1 = {};
|
||||
_context2.t2 = event.args;
|
||||
_context2.t3 = event.args._timeout.toNumber();
|
||||
_context2.next = 6;
|
||||
return _this.getOrderStatus(event.args._id).then(function (status) {
|
||||
return status.toNumber();
|
||||
});
|
||||
|
||||
case 6:
|
||||
_context2.t4 = _context2.sent;
|
||||
_context2.next = 9;
|
||||
return _this.verifyOrderPayment(event.args._id).then(function (received) {
|
||||
return received;
|
||||
});
|
||||
|
||||
case 9:
|
||||
_context2.t5 = _context2.sent;
|
||||
_context2.t6 = {
|
||||
timeout: _context2.t3,
|
||||
status: _context2.t4,
|
||||
paid: _context2.t5,
|
||||
key: null
|
||||
};
|
||||
return _context2.abrupt('return', (0, _context2.t0)(_context2.t1, _context2.t2, _context2.t6));
|
||||
|
||||
case 12:
|
||||
case 'end':
|
||||
return _context2.stop();
|
||||
}
|
||||
}
|
||||
}, _callee2, _this);
|
||||
}));
|
||||
|
||||
return function (_x2) {
|
||||
return _ref3.apply(this, arguments);
|
||||
};
|
||||
}());
|
||||
|
||||
console.debug('got orders: ', orders);
|
||||
return _context3.abrupt('return', orders);
|
||||
|
||||
case 11:
|
||||
case 'end':
|
||||
return _context3.stop();
|
||||
}
|
||||
}
|
||||
}, _callee3, this);
|
||||
}));
|
||||
|
||||
function getConsumerOrders(_x) {
|
||||
return _ref2.apply(this, arguments);
|
||||
}
|
||||
|
||||
return getConsumerOrders;
|
||||
}()
|
||||
|
||||
// Transactions with gas cost
|
||||
|
||||
}, {
|
||||
key: 'requestTokens',
|
||||
value: function requestTokens(senderAddress, numTokens) {
|
||||
return this.oceanMarket.requestTokens(numTokens, { from: senderAddress });
|
||||
}
|
||||
}, {
|
||||
key: 'registerDataAsset',
|
||||
value: function () {
|
||||
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(name, description, price, publisherAddress) {
|
||||
var assetId, result;
|
||||
return _regenerator2.default.wrap(function _callee4$(_context4) {
|
||||
while (1) {
|
||||
switch (_context4.prev = _context4.next) {
|
||||
case 0:
|
||||
_context4.next = 2;
|
||||
return this.oceanMarket.generateId(name + description);
|
||||
|
||||
case 2:
|
||||
assetId = _context4.sent;
|
||||
_context4.next = 5;
|
||||
return this.oceanMarket.register(assetId, price, { from: publisherAddress, gas: this.defaultGas });
|
||||
|
||||
case 5:
|
||||
result = _context4.sent;
|
||||
|
||||
console.log('registered: ', result);
|
||||
return _context4.abrupt('return', assetId);
|
||||
|
||||
case 8:
|
||||
case 'end':
|
||||
return _context4.stop();
|
||||
}
|
||||
}
|
||||
}, _callee4, this);
|
||||
}));
|
||||
|
||||
function registerDataAsset(_x3, _x4, _x5, _x6) {
|
||||
return _ref4.apply(this, arguments);
|
||||
}
|
||||
|
||||
return registerDataAsset;
|
||||
}()
|
||||
}, {
|
||||
key: 'sendPayment',
|
||||
value: function () {
|
||||
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(assetId, order, publisherAddress, senderAddress) {
|
||||
var assetPrice;
|
||||
return _regenerator2.default.wrap(function _callee5$(_context5) {
|
||||
while (1) {
|
||||
switch (_context5.prev = _context5.next) {
|
||||
case 0:
|
||||
_context5.next = 2;
|
||||
return this.oceanMarket.getAssetPrice(assetId).then(function (price) {
|
||||
return price.toNumber();
|
||||
});
|
||||
|
||||
case 2:
|
||||
assetPrice = _context5.sent;
|
||||
|
||||
this.oceanMarket.sendPayment(order.id, publisherAddress, assetPrice, order.timeout, {
|
||||
from: senderAddress,
|
||||
gas: 2000000
|
||||
});
|
||||
|
||||
case 4:
|
||||
case 'end':
|
||||
return _context5.stop();
|
||||
}
|
||||
}
|
||||
}, _callee5, this);
|
||||
}));
|
||||
|
||||
function sendPayment(_x7, _x8, _x9, _x10) {
|
||||
return _ref5.apply(this, arguments);
|
||||
}
|
||||
|
||||
return sendPayment;
|
||||
}()
|
||||
}, {
|
||||
key: 'cancelAccessRequest',
|
||||
value: function cancelAccessRequest(orderId, senderAddress) {
|
||||
return this.oceanAuth.cancelAccessRequest(orderId, { from: senderAddress });
|
||||
}
|
||||
}, {
|
||||
key: 'orchestrateResourcePurchase',
|
||||
value: function orchestrateResourcePurchase(assetId, publisherId, price, privateKey, publicKey, timeout, senderAddress, initialRequestEventHandler, accessCommittedEventHandler, tokenPublishedEventHandler) {
|
||||
var _this2 = this;
|
||||
|
||||
var oceanToken = this.oceanToken,
|
||||
oceanMarket = this.oceanMarket,
|
||||
oceanAuth = this.oceanAuth;
|
||||
// Allow OceanMarket contract to transfer funds on the consumer's behalf
|
||||
|
||||
oceanToken.approve(oceanMarket.address, price, { from: senderAddress, gas: 2000000 });
|
||||
// Submit the access request
|
||||
oceanAuth.initiateAccessRequest(assetId, publisherId, publicKey, timeout, { from: senderAddress, gas: 1000000 });
|
||||
|
||||
var resourceFilter = { _resourceId: assetId, _consumer: senderAddress };
|
||||
var initRequestEvent = oceanAuth.AccessConsentRequested(resourceFilter);
|
||||
var order = {};
|
||||
this._listenOnce(initRequestEvent, 'AccessConsentRequested', function (result, error) {
|
||||
order = initialRequestEventHandler(result, error);
|
||||
var requestIdFilter = { _id: order.id };
|
||||
var accessCommittedEvent = oceanAuth.AccessRequestCommitted(requestIdFilter);
|
||||
var tokenPublishedEvent = oceanAuth.EncryptedTokenPublished(requestIdFilter);
|
||||
_this2._listenOnce(accessCommittedEvent, 'AccessRequestCommitted', function (result, error) {
|
||||
accessCommittedEventHandler(result, order, error);
|
||||
});
|
||||
_this2._listenOnce(tokenPublishedEvent, 'EncryptedTokenPublished', function (result, error) {
|
||||
tokenPublishedEventHandler(result, order, error);
|
||||
});
|
||||
});
|
||||
return order;
|
||||
}
|
||||
|
||||
// Helper functions (private)
|
||||
|
||||
}, {
|
||||
key: '_listenOnce',
|
||||
value: function _listenOnce(event, eventName, callback) {
|
||||
event.watch(function (error, result) {
|
||||
event.stopWatching();
|
||||
if (error) {
|
||||
console.log('Error in keeper ' + eventName + ' event: ', error);
|
||||
}
|
||||
callback(result, error);
|
||||
});
|
||||
}
|
||||
}]);
|
||||
return OceanKeeper;
|
||||
}();
|
||||
|
||||
exports.default = OceanKeeper;
|
19
dist/squid.js
vendored
Normal file
19
dist/squid.js
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.OceanKeeper = exports.OceanAgent = undefined;
|
||||
|
||||
var _oceanAgent = require('./ocean-agent');
|
||||
|
||||
var _oceanAgent2 = _interopRequireDefault(_oceanAgent);
|
||||
|
||||
var _oceanKeeper = require('./ocean-keeper');
|
||||
|
||||
var _oceanKeeper2 = _interopRequireDefault(_oceanKeeper);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
exports.OceanAgent = _oceanAgent2.default;
|
||||
exports.OceanKeeper = _oceanKeeper2.default;
|
5619
package-lock.json
generated
Normal file
5619
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
34
package.json
Normal file
34
package.json
Normal file
@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@oceanprotocol/keeper-js",
|
||||
"version": "0.0.3",
|
||||
"description": "Ocean Javascript Client",
|
||||
"main": "dist/squid.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start:dev": "babel src --watch --out-dir dist",
|
||||
"build": "babel src --out-dir dist"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/oceanprotocol/ocean-client-js.git"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"bugs": {
|
||||
"url": "https://github.com/oceanprotocol/ocean-client-js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/oceanprotocol/ocean-client-js#readme",
|
||||
"dependencies": {
|
||||
"@oceanprotocol/keeper-contracts": "^0.1.0",
|
||||
"truffle-contract": "^3.0.6",
|
||||
"web3": "^0.20.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-cli": "^6.26.0",
|
||||
"babel-core": "^6.26.3",
|
||||
"babel-plugin-transform-runtime": "^6.23.0",
|
||||
"babel-preset-es2015": "^6.24.1",
|
||||
"babel-preset-stage-2": "^6.24.1"
|
||||
}
|
||||
}
|
19
src/contractLoader.js
Normal file
19
src/contractLoader.js
Normal file
@ -0,0 +1,19 @@
|
||||
import TruffleContract from 'truffle-contract'
|
||||
|
||||
const contracts = []
|
||||
|
||||
export default class ContractLoader {
|
||||
static async _doLoad(what, where, provider) {
|
||||
// console.log("Loading", what, "from", where)
|
||||
/* eslint-disable-next-line */
|
||||
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}`)
|
||||
const contract = TruffleContract(artifact)
|
||||
contract.setProvider(provider)
|
||||
contracts[what] = await contract.at(artifact.address)
|
||||
return contracts[what]
|
||||
}
|
||||
|
||||
static load(what, where, provider) {
|
||||
return contracts[what] || ContractLoader._doLoad(what, where, provider)
|
||||
}
|
||||
}
|
36
src/ocean-agent.js
Normal file
36
src/ocean-agent.js
Normal file
@ -0,0 +1,36 @@
|
||||
/* global fetch */
|
||||
|
||||
export default class OceanAgent {
|
||||
constructor(connectionUrl) {
|
||||
this.assetsUrl = connectionUrl + '/assets'
|
||||
}
|
||||
|
||||
getAssetsMetadata() {
|
||||
return fetch(this.assetsUrl + '/metadata', { method: 'GET' })
|
||||
.then(res => res.json())
|
||||
.then(data => JSON.parse(data))
|
||||
}
|
||||
|
||||
publishDataAsset(asset) {
|
||||
return fetch(this.assetsUrl + '/metadata',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(asset),
|
||||
headers: { 'Content-type': 'application/json' }
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Success:', response)
|
||||
if (response.ok) {
|
||||
console.log('Success:', response)
|
||||
return true
|
||||
}
|
||||
console.log('Failed: ', response.status, response.statusText)
|
||||
return false
|
||||
// throw new Error(response.statusText ? response.statusText : `publish asset failed with status ${response.status}`)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log(`Publish asset to ocean database could not be completed: ${error.message()}`)
|
||||
return false
|
||||
})
|
||||
}
|
||||
}
|
178
src/ocean-keeper.js
Normal file
178
src/ocean-keeper.js
Normal file
@ -0,0 +1,178 @@
|
||||
import Web3 from 'web3'
|
||||
import ContractLoader from './contractLoader'
|
||||
|
||||
const DEFAULT_GAS = 300000
|
||||
|
||||
export default class OceanKeeper {
|
||||
constructor(uri, network) {
|
||||
const web3Provider = new Web3.providers.HttpProvider(uri)
|
||||
this.web3 = new Web3(web3Provider)
|
||||
this.defaultGas = DEFAULT_GAS
|
||||
this.network = network || 'development'
|
||||
}
|
||||
|
||||
async initContracts() {
|
||||
this.oceanToken = await ContractLoader.load('OceanToken', this.network, this.web3.currentProvider)
|
||||
this.oceanMarket = await ContractLoader.load('OceanMarket', this.network, this.web3.currentProvider)
|
||||
this.oceanAuth = await ContractLoader.load('OceanAuth', this.network, this.web3.currentProvider)
|
||||
|
||||
return {
|
||||
oceanToken: this.oceanToken,
|
||||
oceanMarket: this.oceanMarket,
|
||||
oceanAuth: this.oceanAuth
|
||||
}
|
||||
}
|
||||
|
||||
// web3 wrappers
|
||||
sign(accountAddress, message) {
|
||||
return this.web3.eth.sign(accountAddress, message)
|
||||
}
|
||||
|
||||
getMessageHash(message) {
|
||||
return this.web3.sha3(`\x19Ethereum Signed Message:\n${message.length}${message}`)
|
||||
}
|
||||
|
||||
// call functions (costs no gas)
|
||||
checkAsset(assetId) {
|
||||
return this.oceanMarket.checkAsset(assetId)
|
||||
}
|
||||
|
||||
getBalance(accountAddress) {
|
||||
return this.oceanToken.balanceOf.call(accountAddress)
|
||||
}
|
||||
|
||||
getAssetPrice(assetId) {
|
||||
return this.oceanMarket.getAssetPrice(assetId).then((price) => price.toNumber())
|
||||
}
|
||||
|
||||
getOrderStatus(orderId) {
|
||||
return this.oceanAuth.statusOfAccessRequest(orderId)
|
||||
}
|
||||
|
||||
verifyOrderPayment(orderId) {
|
||||
return this.oceanMarket.verifyPaymentReceived(orderId)
|
||||
}
|
||||
|
||||
getEncryptedAccessToken(orderId, senderAddress) {
|
||||
return this.oceanAuth.getEncryptedAccessToken(orderId, { from: senderAddress })
|
||||
}
|
||||
|
||||
async getConsumerOrders(consumerAddress) {
|
||||
let accessConsentEvent = this.oceanAuth.AccessConsentRequested({ _consumer: consumerAddress }, {
|
||||
fromBlock: 0,
|
||||
toBlock: 'latest'
|
||||
})
|
||||
|
||||
let _resolve = null
|
||||
let _reject = null
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
_resolve = resolve
|
||||
_reject = reject
|
||||
})
|
||||
|
||||
const getEvents = () => {
|
||||
accessConsentEvent.get((error, logs) => {
|
||||
if (error) {
|
||||
_reject(error)
|
||||
throw new Error(error)
|
||||
} else {
|
||||
_resolve(logs)
|
||||
}
|
||||
})
|
||||
return promise
|
||||
}
|
||||
const events = await getEvents().then((events) => events)
|
||||
// let orders = await this.buildOrdersFromEvents(events, consumerAddress).then((result) => result)
|
||||
let orders = events
|
||||
.filter(obj => (obj.args._consumer === consumerAddress))
|
||||
.map(async (event) => ({
|
||||
...event.args,
|
||||
timeout: event.args._timeout.toNumber(),
|
||||
status: await this.getOrderStatus(event.args._id).then((status) => status.toNumber()),
|
||||
paid: await this.verifyOrderPayment(event.args._id).then((received) => received),
|
||||
key: null
|
||||
}))
|
||||
console.debug('got orders: ', orders)
|
||||
return orders
|
||||
}
|
||||
|
||||
// Transactions with gas cost
|
||||
requestTokens(senderAddress, numTokens) {
|
||||
return this.oceanMarket.requestTokens(numTokens, { from: senderAddress })
|
||||
}
|
||||
|
||||
async registerDataAsset(name, description, price, publisherAddress) {
|
||||
const assetId = await this.oceanMarket.generateId(name + description)
|
||||
const result = await this.oceanMarket.register(
|
||||
assetId,
|
||||
price,
|
||||
{ from: publisherAddress, gas: this.defaultGas }
|
||||
)
|
||||
console.log('registered: ', result)
|
||||
return assetId
|
||||
}
|
||||
|
||||
async sendPayment(assetId, order, publisherAddress, senderAddress) {
|
||||
let assetPrice = await this.oceanMarket.getAssetPrice(assetId).then((price) => price.toNumber())
|
||||
this.oceanMarket.sendPayment(order.id, publisherAddress, assetPrice, order.timeout, {
|
||||
from: senderAddress,
|
||||
gas: 2000000
|
||||
})
|
||||
}
|
||||
|
||||
cancelAccessRequest(orderId, senderAddress) {
|
||||
return this.oceanAuth.cancelAccessRequest(orderId, { from: senderAddress })
|
||||
}
|
||||
|
||||
orchestrateResourcePurchase(
|
||||
assetId, publisherId, price, privateKey, publicKey, timeout, senderAddress,
|
||||
initialRequestEventHandler, accessCommittedEventHandler, tokenPublishedEventHandler) {
|
||||
const { oceanToken, oceanMarket, oceanAuth } = this
|
||||
// Allow OceanMarket contract to transfer funds on the consumer's behalf
|
||||
oceanToken.approve(oceanMarket.address, price, { from: senderAddress, gas: 2000000 })
|
||||
// Submit the access request
|
||||
oceanAuth.initiateAccessRequest(
|
||||
assetId, publisherId, publicKey,
|
||||
timeout, { from: senderAddress, gas: 1000000 }
|
||||
)
|
||||
|
||||
const resourceFilter = { _resourceId: assetId, _consumer: senderAddress }
|
||||
const initRequestEvent = oceanAuth.AccessConsentRequested(resourceFilter)
|
||||
let order = {}
|
||||
this._listenOnce(
|
||||
initRequestEvent,
|
||||
'AccessConsentRequested',
|
||||
(result, error) => {
|
||||
order = initialRequestEventHandler(result, error)
|
||||
const requestIdFilter = { _id: order.id }
|
||||
const accessCommittedEvent = oceanAuth.AccessRequestCommitted(requestIdFilter)
|
||||
const tokenPublishedEvent = oceanAuth.EncryptedTokenPublished(requestIdFilter)
|
||||
this._listenOnce(
|
||||
accessCommittedEvent,
|
||||
'AccessRequestCommitted',
|
||||
(result, error) => {
|
||||
accessCommittedEventHandler(result, order, error)
|
||||
}
|
||||
)
|
||||
this._listenOnce(
|
||||
tokenPublishedEvent,
|
||||
'EncryptedTokenPublished',
|
||||
(result, error) => {
|
||||
tokenPublishedEventHandler(result, order, error)
|
||||
}
|
||||
)
|
||||
})
|
||||
return order
|
||||
}
|
||||
|
||||
// Helper functions (private)
|
||||
_listenOnce(event, eventName, callback) {
|
||||
event.watch((error, result) => {
|
||||
event.stopWatching()
|
||||
if (error) {
|
||||
console.log(`Error in keeper ${eventName} event: `, error)
|
||||
}
|
||||
callback(result, error)
|
||||
})
|
||||
}
|
||||
}
|
7
src/squid.js
Normal file
7
src/squid.js
Normal file
@ -0,0 +1,7 @@
|
||||
import OceanAgent from './ocean-agent'
|
||||
import OceanKeeper from './ocean-keeper'
|
||||
|
||||
export {
|
||||
OceanAgent,
|
||||
OceanKeeper
|
||||
}
|
Loading…
Reference in New Issue
Block a user