1
0
mirror of https://github.com/oceanprotocol/react.git synced 2024-06-10 11:25:21 +02:00
react/src/utils/dtUtils.ts

80 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-08-04 13:37:12 +02:00
import { Logger, Ocean, Account } from '@oceanprotocol/lib'
2020-08-04 14:00:12 +02:00
import { Decimal } from 'decimal.js'
2020-08-04 13:49:45 +02:00
export async function getCheapestPool(
ocean: Ocean,
accountId: string,
dataTokenAddress: string
): Promise<{ poolAddress: string; poolPrice: string }> {
const tokenPools = await ocean.pool.searchPoolforDT(
accountId,
dataTokenAddress
)
2020-08-04 13:37:12 +02:00
Logger.log('DT Pool found', tokenPools)
let cheapestPoolAddress
2020-08-04 14:00:12 +02:00
let cheapestPoolPrice = new Decimal(999999999999)
2020-08-04 13:37:12 +02:00
if (tokenPools) {
for (let i = 0; i < tokenPools.length; i++) {
2020-08-04 13:49:45 +02:00
const poolPrice = await ocean.pool.getOceanNeeded(
accountId,
tokenPools[i],
'1'
)
2020-08-04 14:00:12 +02:00
const decimalPoolPrice = new Decimal(poolPrice)
2020-08-04 13:37:12 +02:00
Logger.log('Pool price ', tokenPools[i], poolPrice)
2020-08-04 14:00:12 +02:00
if (decimalPoolPrice < cheapestPoolPrice) {
cheapestPoolPrice = decimalPoolPrice
2020-08-04 13:37:12 +02:00
cheapestPoolAddress = tokenPools[i]
}
}
}
2020-08-04 13:49:45 +02:00
return {
poolAddress: cheapestPoolAddress,
poolPrice: cheapestPoolPrice.toString()
}
2020-08-04 13:37:12 +02:00
}
2020-08-04 13:49:45 +02:00
export async function getBestDataTokenPrice(
ocean: Ocean,
accountId: string,
dataTokenAddress: string
): Promise<string> {
2020-08-04 13:37:12 +02:00
const bestPool = await getCheapestPool(ocean, accountId, dataTokenAddress)
return bestPool.poolPrice
}
2020-08-04 13:49:45 +02:00
export async function checkAndBuyDT(
ocean: Ocean,
dataTokenAddress: string,
account: Account
) {
const userOwnedTokens = await ocean.accounts.getTokenBalance(
dataTokenAddress,
account
)
2020-08-04 13:37:12 +02:00
Logger.log(`User has ${userOwnedTokens} tokens`)
let cheapestPool
if (userOwnedTokens === '0') {
2020-08-04 13:49:45 +02:00
cheapestPool = await getCheapestPool(
ocean,
account.getId(),
dataTokenAddress
)
Decimal.set({ precision: 5 })
const price = new Decimal(cheapestPool.poolPrice).times(1.05).toString()
const maxPrice = new Decimal(cheapestPool.poolPrice).times(2).toString()
Logger.log('Buying token', cheapestPool, account.getId(), price)
const buyResponse = await ocean.pool.buyDT(
account.getId(),
cheapestPool.poolAddress,
'1',
price,
maxPrice
)
2020-08-04 13:37:12 +02:00
Logger.log('DT buy response', buyResponse)
2020-08-04 13:49:45 +02:00
return buyResponse
2020-08-04 13:37:12 +02:00
}
2020-08-04 13:49:45 +02:00
}