1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00

adapted changes from squid discussion, updated interface definition

This commit is contained in:
Sebastian Gerske 2018-10-18 13:06:52 +02:00
parent 4901c65079
commit 7f5f7606dc
9 changed files with 102 additions and 114 deletions

View File

@ -38,9 +38,10 @@ export default class OceanMarket extends ContractWrapperBase {
} }
public async payOrder(order: Order, publisherAddress: string, public async payOrder(order: Order, publisherAddress: string,
price: number, consumerAddress: string): Promise<Receipt> { price: number, consumerAddress: string,
timeout: number): Promise<Receipt> {
return this.sendTransaction("sendPayment", consumerAddress, [ return this.sendTransaction("sendPayment", consumerAddress, [
order.getId(), publisherAddress, price, order.getTimeout(), order.getId(), publisherAddress, price, timeout,
]) ])
} }
} }

View File

@ -11,7 +11,7 @@ export default class Account extends OceanBase {
return (await Keeper.getInstance()).token.balanceOf(this.id) return (await Keeper.getInstance()).token.balanceOf(this.id)
} }
public async getEthBalance(): Promise<number> { public async getEtherBalance(): Promise<number> {
// Logger.log("getting balance for", account); // Logger.log("getting balance for", account);
return Web3Provider.getWeb3().eth return Web3Provider.getWeb3().eth
.getBalance(this.id, "latest") .getBalance(this.id, "latest")
@ -25,7 +25,7 @@ export default class Account extends OceanBase {
if (!this.balance) { if (!this.balance) {
this.balance = { this.balance = {
eth: await this.getEthBalance(), eth: await this.getEtherBalance(),
ocn: await this.getOceanBalance(), ocn: await this.getOceanBalance(),
} as Balance } as Balance
} }
@ -34,7 +34,8 @@ export default class Account extends OceanBase {
} }
// Transactions with gas cost // Transactions with gas cost
public async requestTokens(amount: number): Promise<boolean> { public async requestTokens(amount: number): Promise<number> {
return (await Keeper.getInstance()).market.requestTokens(amount, this.id) await (await Keeper.getInstance()).market.requestTokens(amount, this.id)
return amount
} }
} }

View File

@ -1,10 +1,6 @@
import * as EthCrypto from "eth-crypto" import * as EthCrypto from "eth-crypto"
import * as EthEcies from "eth-ecies"
import * as EthjsUtil from "ethereumjs-util" import * as EthjsUtil from "ethereumjs-util"
import * as JWT from "jsonwebtoken"
import Keeper from "../keeper/Keeper" import Keeper from "../keeper/Keeper"
import Web3Provider from "../keeper/Web3Provider"
import ProviderProvider from "../provider/ProviderProvider"
import Logger from "../utils/Logger" import Logger from "../utils/Logger"
import Account from "./Account" import Account from "./Account"
import OceanBase from "./OceanBase" import OceanBase from "./OceanBase"
@ -19,11 +15,6 @@ export default class Asset extends OceanBase {
super() super()
} }
public async isActive(): Promise<boolean> {
const {market} = await Keeper.getInstance()
return market.isAssetActive(this.getId())
}
public async purchase(consumer: Account, timeout: number): Promise<Order> { public async purchase(consumer: Account, timeout: number): Promise<Order> {
const {token, market, auth} = await Keeper.getInstance() const {token, market, auth} = await Keeper.getInstance()
@ -62,42 +53,4 @@ export default class Asset extends OceanBase {
return order return order
} }
public async consume(order: Order, consumer: Account): Promise<string> {
const {auth} = await Keeper.getInstance()
const encryptedAccessToken = await auth.getEncryptedAccessToken(order.getId(), consumer.getId())
// grab the access token from acl contract
const tokenNo0x = encryptedAccessToken.slice(2)
const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex")
const privateKey = order.getKey().privateKey.slice(2)
const accessTokenEncoded: string =
EthEcies.decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer).toString()
const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object
if (!accessToken) {
throw new Error(`AccessToken is not an jwt: ${accessTokenEncoded}`)
}
const signature = Web3Provider.getWeb3().eth.sign(encryptedAccessToken, consumer.getId())
const encryptedAccessTokenSha3 = Web3Provider.getWeb3().utils.sha3(encryptedAccessToken)
// Download the data set from the provider using the url in the access token
// decode the access token, grab the service_endpoint, request_id,
// payload keys: ['consumerId', 'fixed_msg', 'sigEncJWT', 'jwt']
const payload = JSON.stringify({
consumerId: consumer.getId(),
fixed_msg: encryptedAccessTokenSha3,
sigEncJWT: signature,
jwt: accessTokenEncoded,
})
const accessUrl = await ProviderProvider.getProvider().getAccessUrl(accessToken, payload)
Logger.log("consume url: ", accessUrl)
return accessUrl
}
} }

View File

@ -54,8 +54,8 @@ export default class Ocean {
return assetId return assetId
} }
public async getOrdersByConsumer(consumer: Account): Promise<Order[]> { public async getOrdersByAccount(consumer: Account): Promise<Order[]> {
const {auth, market} = this.keeper const {auth} = this.keeper
Logger.log("Getting orders") Logger.log("Getting orders")
@ -80,7 +80,6 @@ export default class Ocean {
null, null) null, null)
order.setId(returnValues._id) order.setId(returnValues._id)
order.setPaid(await market.verifyOrderPayment(returnValues._id))
return order return order
}), }),

View File

@ -1,6 +1,9 @@
import * as EthEcies from "eth-ecies" import * as EthEcies from "eth-ecies"
import * as JWT from "jsonwebtoken"
import Keeper from "../keeper/Keeper" import Keeper from "../keeper/Keeper"
import Web3Provider from "../keeper/Web3Provider"
import AccessStatus from "../models/AccessStatus" import AccessStatus from "../models/AccessStatus"
import ProviderProvider from "../provider/ProviderProvider"
import Logger from "../utils/Logger" import Logger from "../utils/Logger"
import Account from "./Account" import Account from "./Account"
import Asset from "./Asset" import Asset from "./Asset"
@ -8,8 +11,6 @@ import OceanBase from "./OceanBase"
export default class Order extends OceanBase { export default class Order extends OceanBase {
private paid: boolean
constructor(private asset: Asset, private timeout: number, constructor(private asset: Asset, private timeout: number,
private pubkey: string, private key: any) { private pubkey: string, private key: any) {
super() super()
@ -20,33 +21,18 @@ export default class Order extends OceanBase {
return auth.getOrderStatus(this.id) return auth.getOrderStatus(this.id)
} }
public setPaid(paid: boolean) {
this.paid = paid
}
public getPaid() {
return this.paid
}
public getTimeout() {
return this.timeout
}
public getKey() {
return this.key
}
public async pay(consumer: Account): Promise<string> { public async pay(consumer: Account): Promise<string> {
const {market} = await Keeper.getInstance() const {market} = await Keeper.getInstance()
Logger.log( Logger.log(
`Sending payment: ${this.getId()} ${this.asset.publisher.getId()} ${this.asset.price} ${this.timeout}`, `Sending payment: ${this.getId()} ${this.asset.publisher.getId()} ${this.asset.price} ${this.timeout}`,
) )
const payReceipt = await market.payOrder(this, this.asset.publisher.getId(), this.asset.price, consumer.getId()) const payReceipt =
await market.payOrder(this, this.asset.publisher.getId(), this.asset.price, consumer.getId(), this.timeout)
return payReceipt.events.PaymentReceived.returnValues._paymentId return payReceipt.events.PaymentReceived.returnValues._paymentId
} }
public async commit(accessToken: string) { public async commit(accessToken: string): Promise<boolean> {
const {auth} = await Keeper.getInstance() const {auth} = await Keeper.getInstance()
const commitAccessRequestReceipt = await auth.commitAccessRequest(this, this.asset.publisher.getId()) const commitAccessRequestReceipt = await auth.commitAccessRequest(this, this.asset.publisher.getId())
if (commitAccessRequestReceipt.events.AccessRequestRejected) { if (commitAccessRequestReceipt.events.AccessRequestRejected) {
@ -65,5 +51,47 @@ export default class Order extends OceanBase {
EthEcies.encrypt(new Buffer(pubKey, "hex"), new Buffer(accessToken)).toString("hex") EthEcies.encrypt(new Buffer(pubKey, "hex"), new Buffer(accessToken)).toString("hex")
await auth.deliverAccessToken(this.getId(), `0x${encryptedAccessToken}`, this.asset.publisher.getId()) await auth.deliverAccessToken(this.getId(), `0x${encryptedAccessToken}`, this.asset.publisher.getId())
return true
} }
public async consume(consumer: Account): Promise<string> {
const {auth} = await Keeper.getInstance()
const encryptedAccessToken = await auth.getEncryptedAccessToken(this.getId(), consumer.getId())
// grab the access token from acl contract
const tokenNo0x = encryptedAccessToken.slice(2)
const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex")
const privateKey = this.key.privateKey.slice(2)
const accessTokenEncoded: string =
EthEcies.decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer).toString()
const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object
if (!accessToken) {
throw new Error(`AccessToken is not an jwt: ${accessTokenEncoded}`)
}
const signature = Web3Provider.getWeb3().eth.sign(encryptedAccessToken, consumer.getId())
const encryptedAccessTokenSha3 = Web3Provider.getWeb3().utils.sha3(encryptedAccessToken)
// Download the data set from the provider using the url in the access token
// decode the access token, grab the service_endpoint, request_id,
// payload keys: ['consumerId', 'fixed_msg', 'sigEncJWT', 'jwt']
const payload = JSON.stringify({
consumerId: consumer.getId(),
fixed_msg: encryptedAccessTokenSha3,
sigEncJWT: signature,
jwt: accessTokenEncoded,
})
const accessUrl = await ProviderProvider.getProvider().getAccessUrl(accessToken, payload)
Logger.log("consume url: ", accessUrl)
return accessUrl
}
} }

View File

@ -23,9 +23,9 @@ describe("Account", () => {
it("should get initial ocean balance", async () => { it("should get initial ocean balance", async () => {
const balance = await accounts[0].getOceanBalance() const balance = await accounts[8].getOceanBalance()
assert(0 === balance) assert(0 === balance, `Expected 0 got ${balance}`)
}) })
it("should get the correct balance", async () => { it("should get the correct balance", async () => {
@ -44,7 +44,7 @@ describe("Account", () => {
it("should get initial ether balance", async () => { it("should get initial ether balance", async () => {
const account: Account = accounts[9] const account: Account = accounts[9]
const balance = await account.getEthBalance() const balance = await account.getEtherBalance()
const web3 = Web3Provider.getWeb3() const web3 = Web3Provider.getWeb3()
assert(Number(web3.utils.toWei("100", "ether")) === balance) assert(Number(web3.utils.toWei("100", "ether")) === balance)
@ -63,4 +63,16 @@ describe("Account", () => {
assert(0 === balance.ocn) assert(0 === balance.ocn)
}) })
}) })
describe("#requestTokens()", () => {
it("should return the amount of tokens granted", async () => {
const tokens = 500
const account: Account = accounts[0]
const tokensGranted: number = await account.requestTokens(tokens)
assert(tokensGranted === tokens)
})
})
}) })

View File

@ -13,7 +13,6 @@ const testName = "Test Asset 2"
const testDescription = "This asset is pure owange" const testDescription = "This asset is pure owange"
const testPrice = 100 const testPrice = 100
const timeout = 100000 const timeout = 100000
const accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1Mzk3ODcxMDEsImV4cCI6NDcyNjk5NjcwNCwiYXVkIjoiIiwic3ViIjoiIiwic2VydmljZV9lbmRwb2ludCI6Imh0dHA6Ly9hZGFzZCIsInJlc291cmNlX2lkIjoiMTIzNDUifQ.2H3TRC3CAToVE9divSckwHi_HNvgOHKrtJPo8128qrKBHTk7YYb0UNfVCuYqwhGR"
let ocean: Ocean let ocean: Ocean
let testAsset: Asset let testAsset: Asset
@ -35,22 +34,6 @@ before(async () => {
describe("Asset", () => { describe("Asset", () => {
describe("#isActive()", () => {
it("should return true on new asset", async () => {
const isAssetActive = await testAsset.isActive()
assert(true === isAssetActive)
})
it("should return false on unknown asset", async () => {
const isAssetActive = await new Asset(testName, testDescription, testPrice, testPublisher)
.isActive()
assert(false === isAssetActive)
})
})
describe("#purchase()", () => { describe("#purchase()", () => {
it("should purchase an asset", async () => { it("should purchase an asset", async () => {
@ -61,20 +44,4 @@ describe("Asset", () => {
assert(order) assert(order)
}) })
}) })
describe("#consume()", () => {
it("should consume an asset", async () => {
const consumerAccount = accounts[5]
await consumerAccount.requestTokens(testAsset.price)
// place order - consumer
const order: Order = await testAsset.purchase(consumerAccount, timeout)
// commit order - provider
await order.commit(accessToken)
// pay order - consumer
await order.pay(consumerAccount)
const url = await testAsset.consume(order, consumerAccount)
assert(url)
})
})
}) })

View File

@ -29,6 +29,17 @@ before(async () => {
describe("Ocean", () => { describe("Ocean", () => {
describe("#getInstance()", () => {
it("should list accounts", async () => {
const ocn = Ocean.getInstance(config)
assert(ocn)
})
})
describe("#getAccounts()", () => { describe("#getAccounts()", () => {
it("should list accounts", async () => { it("should list accounts", async () => {
@ -51,6 +62,7 @@ describe("Ocean", () => {
assert(assetId.length === 66) assert(assetId.length === 66)
assert(assetId.startsWith("0x")) assert(assetId.startsWith("0x"))
}) })
}) })
describe("#getOrdersByConsumer()", () => { describe("#getOrdersByConsumer()", () => {
@ -63,7 +75,7 @@ describe("Ocean", () => {
await ocean.register(asset) await ocean.register(asset)
const order: Order = await asset.purchase(testConsumer, timeout) const order: Order = await asset.purchase(testConsumer, timeout)
const orders = await ocean.getOrdersByConsumer(testConsumer) const orders = await ocean.getOrdersByAccount(testConsumer)
assert(orders.length === 1) assert(orders.length === 1)
assert(orders[0].getId() === order.getId()) assert(orders[0].getId() === order.getId())

View File

@ -12,7 +12,7 @@ const testName = "Order Test Asset"
const testDescription = "This asset is pure owange" const testDescription = "This asset is pure owange"
const testPrice = 100 const testPrice = 100
const timeout = 1000000 const timeout = 1000000
const accessToken = "eyJhbGciOiJIUzI1" const accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1Mzk3ODcxMDEsImV4cCI6NDcyNjk5NjcwNCwiYXVkIjoiIiwic3ViIjoiIiwic2VydmljZV9lbmRwb2ludCI6Imh0dHA6Ly9hZGFzZCIsInJlc291cmNlX2lkIjoiMTIzNDUifQ.2H3TRC3CAToVE9divSckwHi_HNvgOHKrtJPo8128qrKBHTk7YYb0UNfVCuYqwhGR"
let ocean: Ocean let ocean: Ocean
let testAsset: Asset let testAsset: Asset
@ -83,4 +83,19 @@ describe("Order", () => {
}) })
}) })
describe("#consume()", () => {
it("should consume an asset", async () => {
const consumerAccount = accounts[5]
await consumerAccount.requestTokens(testAsset.price)
// place order - consumer
const order: Order = await testAsset.purchase(consumerAccount, timeout)
// commit order - provider
await order.commit(accessToken)
// pay order - consumer
await order.pay(consumerAccount)
const url = await order.consume(consumerAccount)
assert(url)
})
})
}) })