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

191 lines
6.8 KiB
TypeScript
Raw Normal View History

2018-10-02 10:06:26 +02:00
import * as EthCrypto from "eth-crypto"
import EthEcies from "eth-ecies"
import * as EthjsUtil from "ethereumjs-util"
import JWT from "jsonwebtoken"
import Keeper from "../keeper/Keeper"
import Asset from "../models/Asset"
import OrderModel from "../models/Order"
import Logger from "../utils/Logger"
declare var fetch
export default class Order {
private static create(asset: Asset, args, key): OrderModel {
2018-10-02 10:06:26 +02:00
Logger.log("keeper AccessConsentRequested event received on asset: ", asset.assetId, "\nevent:", args)
const accessId = args._id
Logger.log("got new access request id: ", accessId)
return {
id: accessId,
assetId: asset.assetId,
asset,
timeout: args._timeout,
pubkey: args._pubKey,
key,
2018-10-02 10:06:26 +02:00
} as OrderModel
}
2018-10-02 10:06:26 +02:00
private keeper: Keeper
constructor(keeper: Keeper) {
2018-10-02 10:06:26 +02:00
this.keeper = keeper
}
public async getOrdersByConsumer(consumerAddress: string) {
2018-10-02 10:06:26 +02:00
const {auth, market} = this.keeper
2018-10-04 13:14:03 +02:00
const accessConsentRequestedData = await auth.getEventData("AccessConsentRequested", {
filter: {
_consumer: consumerAddress,
},
fromBlock: 0,
2018-10-02 10:06:26 +02:00
})
2018-10-04 13:14:03 +02:00
Logger.log("wai", accessConsentRequestedData)
const orders = await Promise.all(
accessConsentRequestedData
.filter((event: any) => (event.args._consumer === consumerAddress))
.map(async (event: any) => ({
...event.args,
timeout: event.args._timeout.toNumber(),
status: await auth.getOrderStatus(event.args._id),
paid: await market.verifyOrderPayment(event.args._id),
key: null,
} as Order
),
),
)
2018-10-02 10:06:26 +02:00
Logger.log("Got orders: ", orders)
return orders
}
public async purchaseAsset(asset: Asset, timeout: number, buyerAddress: string): Promise<OrderModel> {
2018-10-02 10:06:26 +02:00
const {token, market, auth} = this.keeper
2018-10-02 10:06:26 +02:00
const key = EthCrypto.createIdentity()
const publicKey = EthjsUtil.privateToPublic(key.privateKey).toString("hex")
const price = await market.getAssetPrice(asset.assetId)
const isValid = await market.isAssetActive(asset.assetId)
2018-10-02 10:06:26 +02:00
Logger.log("The asset:", asset.assetId, "is it valid?", isValid, "it's price is:", price)
if (!isValid) {
2018-10-02 10:06:26 +02:00
throw new Error("asset not valid")
}
try {
// Allow market contract to transfer funds on the consumer"s behalf
2018-10-02 10:06:26 +02:00
await token.approve(market.getAddress(), price, buyerAddress)
} catch (err) {
2018-10-02 10:06:26 +02:00
Logger.log("token approve", err)
}
try {
// Submit the access request
2018-10-02 10:06:26 +02:00
await auth.initiateAccessRequest(asset, publicKey, timeout, buyerAddress)
} catch (err) {
2018-10-02 10:06:26 +02:00
Logger.log("initiateAccessRequest", err)
}
2018-10-04 13:14:03 +02:00
2018-10-02 10:06:26 +02:00
let order: OrderModel
2018-10-04 13:14:03 +02:00
const finalOrder: OrderModel = await auth.listenToEventOnce(
"AccessConsentRequested", {
filter: {
_resourceId: asset.assetId,
_consumer: buyerAddress,
},
})
.then((accessConsentRequestedResult) => {
2018-10-02 10:06:26 +02:00
order = Order.create(asset, accessConsentRequestedResult.args, key)
2018-10-04 13:14:03 +02:00
return auth.listenToEventOnce("AccessRequestCommitted", {
filter: {
_id: order.id,
},
})
})
.then((accessRequestCommittedResult) => {
2018-10-02 10:06:26 +02:00
return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress)
})
.then(() => {
2018-10-04 13:14:03 +02:00
return auth.listenToEventOnce("EncryptedTokenPublished", {
filter: {
_id: order.id,
},
})
})
.then((result) => {
return this.finalizePurchaseAsset(
result, order, key, buyerAddress,
2018-10-02 10:06:26 +02:00
)
})
2018-10-02 10:06:26 +02:00
return finalOrder
}
private async payAsset(asset: Asset, args, order, buyerAddress) {
2018-10-02 10:06:26 +02:00
const {market} = this.keeper
// send payment
2018-10-02 10:06:26 +02:00
Logger.log("Sending payment: ", order.id, args._id, asset.publisherId, asset.price, order.timeout)
return market.payAsset(asset, order, buyerAddress)
}
private async finalizePurchaseAsset(args, order, key, buyerAddress): Promise<OrderModel> {
2018-10-02 10:06:26 +02:00
const {auth, web3Helper} = this.keeper
// Logger.log('keeper EncryptedTokenPublished event received: ', order.id, eventResult.args)
2018-10-02 10:06:26 +02:00
const encryptedAccessToken = await auth.getEncryptedAccessToken(args._id, buyerAddress)
// grab the access token from acl contract
2018-10-02 10:06:26 +02:00
const tokenNo0x = encryptedAccessToken.slice(2)
const encryptedTokenBuffer = Buffer.from(tokenNo0x, "hex")
2018-10-02 10:06:26 +02:00
const privateKey = key.privateKey.slice(2)
const accessTokenEncoded = EthEcies.Decrypt(Buffer.from(privateKey, "hex"), encryptedTokenBuffer)
const accessToken = JWT.decode(accessTokenEncoded) // Returns a json object
// sign it
2018-10-02 10:06:26 +02:00
const hexEncrToken = `0x${encryptedTokenBuffer.toString("hex")}`
2018-10-02 10:06:26 +02:00
const signature = web3Helper.sign(buyerAddress, hexEncrToken)
const fixedMsgSha = web3Helper.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: buyerAddress,
fixed_msg: fixedMsgSha,
sigEncJWT: signature,
jwt: accessTokenEncoded,
2018-10-02 10:06:26 +02:00
})
const accessUrl = await fetch(`${accessToken.service_endpoint}/${accessToken.resource_id}`, {
method: "POST",
body: payload,
headers: {
"Content-type": "application/json",
},
})
.then((response: any) => {
if (response.ok) {
2018-10-02 10:06:26 +02:00
return response.text()
}
2018-10-02 10:06:26 +02:00
Logger.log("Failed: ", response.status, response.statusText)
})
.then((consumptionUrl: string) => {
2018-10-02 10:06:26 +02:00
Logger.log("Success accessing consume endpoint: ", consumptionUrl)
return consumptionUrl
})
.catch((error) => {
2018-10-02 10:06:26 +02:00
Logger.error("Error fetching the data asset consumption url: ", error)
})
Logger.log("consume url: ", accessUrl)
order.accessUrl = accessUrl
2018-10-02 10:06:26 +02:00
return order
}
}