1
0
mirror of https://github.com/oceanprotocol/ocean.js.git synced 2024-11-26 20:39:05 +01:00

heleper+ remove old ibs (#1238)

* heleper+ remove old ibs

* fix tests

* fix gaslimt

* fix approve

* fix

* remove console.log

* upate package-lock
This commit is contained in:
mihaisc 2022-01-25 18:32:55 +02:00 committed by GitHub
parent 5b73daad7e
commit 56a3aad20d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 743 additions and 915 deletions

833
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -62,8 +62,6 @@
"cross-fetch": "^3.1.4",
"crypto-js": "^4.0.0",
"decimal.js": "^10.2.1",
"fs": "0.0.1-security",
"save-file": "^2.3.1",
"web3": ">=1.3.5",
"web3-core": "^1.6.1",
"web3-eth-contract": "^1.6.1"
@ -83,6 +81,7 @@
"chai-spies": "^1.0.0",
"cross-env": "^7.0.3",
"eslint": "^7.17.0",
"fs": "0.0.1-security",
"eslint-config-oceanprotocol": "^1.5.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",

View File

@ -0,0 +1,4 @@
export interface DownloadResponse {
data: ArrayBuffer
filename: string
}

View File

@ -5,14 +5,15 @@ import { Contract } from 'web3-eth-contract'
import {
Logger,
getFairGasPrice,
LoggerInstance,
configHelperNetworks,
setContractDefaults
setContractDefaults,
unitsToAmount,
amountToUnits
} from '../../utils'
import BigNumber from 'bignumber.js'
import PoolTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BPool.sol/BPool.json'
import defaultErc20Abi from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json'
import Decimal from 'decimal.js'
import {
CurrentFees,
TokenInOutMarket,
@ -20,6 +21,7 @@ import {
AmountsOutMaxFee
} from '../../interfaces'
import { Config } from '../../models'
import { minAbi } from '../../utils/minAbi'
const MaxUint256 =
'115792089237316195423570985008687907853269984665640564039457584007913129639934'
@ -46,130 +48,6 @@ export class Pool {
this.config = config || configHelperNetworks[0]
}
/**
* Estimate gas cost for approval function
* @param {String} account
* @param {String} tokenAddress
* @param {String} spender
* @param {String} amount
* @param {String} force
* @param {Contract} contractInstance optional contract instance
* @return {Promise<number>}
*/
public async estApprove(
account: string,
tokenAddress: string,
spender: string,
amount: string,
contractInstance?: Contract
): Promise<number> {
const tokenContract =
contractInstance ||
setContractDefaults(
new this.web3.eth.Contract(defaultErc20Abi.abi as AbiItem[], tokenAddress),
this.config
)
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await tokenContract.methods
.approve(spender, amount)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
LoggerInstance.error('estimate gas failed for approve!', e)
}
return estGas
}
/**
* Get Alloance for both Datatoken and Ocean
* @param {String } tokenAdress
* @param {String} owner
* @param {String} spender
*/
public async allowance(
tokenAddress: string,
owner: string,
spender: string
): Promise<string> {
const tokenAbi = defaultErc20Abi.abi as AbiItem[]
const datatoken = setContractDefaults(
new this.web3.eth.Contract(tokenAbi, tokenAddress),
this.config
)
const trxReceipt = await datatoken.methods.allowance(owner, spender).call()
return await this.unitsToAmount(tokenAddress, trxReceipt)
}
/**
* Approve spender to spent amount tokens
* @param {String} account
* @param {String} tokenAddress
* @param {String} spender
* @param {String} amount (always expressed as wei)
* @param {String} force if true, will overwrite any previous allowence. Else, will check if allowence is enough and will not send a transaction if it's not needed
*/
async approve(
account: string,
tokenAddress: string,
spender: string,
amount: string,
force = false
): Promise<TransactionReceipt | string> {
const minABI = [
{
constant: false,
inputs: [
{
name: '_spender',
type: 'address'
},
{
name: '_value',
type: 'uint256'
}
],
name: 'approve',
outputs: [
{
name: '',
type: 'bool'
}
],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
}
] as AbiItem[]
const token = setContractDefaults(
new this.web3.eth.Contract(minABI, tokenAddress),
this.config
)
if (!force) {
const currentAllowence = await this.allowance(tokenAddress, account, spender)
if (new Decimal(currentAllowence).greaterThanOrEqualTo(new Decimal(amount))) {
return currentAllowence
}
}
let result = null
const amountFormatted = await this.amountToUnits(tokenAddress, amount)
const estGas = await this.estApprove(account, tokenAddress, spender, amountFormatted)
try {
result = await token.methods.approve(spender, amountFormatted).send({
from: account,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3, this.config)
})
} catch (e) {
this.logger.error(`ERRPR: Failed to approve spender to spend tokens : ${e.message}`)
}
return result
}
/**
* Get user shares of pool tokens
* @param {String} account
@ -465,7 +343,7 @@ export class Pool {
this.config
)
const result = await pool.methods.getBalance(token).call()
amount = await this.unitsToAmount(token, result)
amount = await unitsToAmount(this.web3, token, result)
} catch (e) {
this.logger.error(`ERROR: Failed to get how many tokens \
are in the pool: ${e.message}`)
@ -588,7 +466,7 @@ export class Pool {
let weight = null
try {
const result = await pool.methods.publishMarketFees(token).call()
weight = await this.unitsToAmount(token, result)
weight = await unitsToAmount(this.web3, token, result)
} catch (e) {
this.logger.error(`ERROR: Failed to get market fees for a token: ${e.message}`)
}
@ -643,7 +521,7 @@ export class Pool {
let weight = null
try {
const result = await pool.methods.communityFees(token).call()
weight = await this.unitsToAmount(token, result)
weight = await unitsToAmount(this.web3, token, result)
} catch (e) {
this.logger.error(`ERROR: Failed to get community fees for a token: ${e.message}`)
}
@ -843,42 +721,6 @@ export class Pool {
return result
}
async amountToUnits(token: string, amount: string): Promise<string> {
try {
const tokenContract = setContractDefaults(
new this.web3.eth.Contract(defaultErc20Abi.abi as AbiItem[], token),
this.config
)
let decimals = await tokenContract.methods.decimals().call()
if (decimals === '0') {
decimals = 18
}
const amountFormatted = new BigNumber(parseInt(amount) * 10 ** decimals)
BigNumber.config({ EXPONENTIAL_AT: 50 })
return amountFormatted.toString()
} catch (e) {
this.logger.error('ERROR: FAILED TO CALL DECIMALS(), USING 18')
}
}
async unitsToAmount(token: string, amount: string): Promise<string> {
try {
const tokenContract = setContractDefaults(
new this.web3.eth.Contract(defaultErc20Abi.abi as AbiItem[], token),
this.config
)
let decimals = await tokenContract.methods.decimals().call()
if (decimals === '0') {
decimals = 18
}
const amountFormatted = new BigNumber(parseInt(amount) / 10 ** decimals)
return amountFormatted.toString()
} catch (e) {
this.logger.error('ERROR: FAILED TO CALL DECIMALS(), USING 18')
}
}
/**
* Estimate gas cost for swapExactAmountIn
* @param {String} address
@ -953,12 +795,14 @@ export class Pool {
this.config
)
amountsInOutMaxFee.tokenAmountIn = await this.amountToUnits(
amountsInOutMaxFee.tokenAmountIn = await amountToUnits(
this.web3,
tokenInOutMarket.tokenIn,
amountsInOutMaxFee.tokenAmountIn
)
amountsInOutMaxFee.minAmountOut = await this.amountToUnits(
amountsInOutMaxFee.minAmountOut = await amountToUnits(
this.web3,
tokenInOutMarket.tokenOut,
amountsInOutMaxFee.minAmountOut
)
@ -1075,12 +919,14 @@ export class Pool {
)
let result = null
amountsInOutMaxFee.maxAmountIn = await this.amountToUnits(
amountsInOutMaxFee.maxAmountIn = await amountToUnits(
this.web3,
tokenInOutMarket.tokenIn,
amountsInOutMaxFee.maxAmountIn
)
amountsInOutMaxFee.tokenAmountOut = await this.amountToUnits(
amountsInOutMaxFee.tokenAmountOut = await amountToUnits(
this.web3,
tokenInOutMarket.tokenOut,
amountsInOutMaxFee.tokenAmountOut
)
@ -1179,7 +1025,7 @@ export class Pool {
const tokens = await this.getFinalTokens(poolAddress)
for (let i = 0; i < 2; i++) {
const amount = await this.amountToUnits(tokens[i], maxAmountsIn[i])
const amount = await amountToUnits(this.web3, tokens[i], maxAmountsIn[i])
weiMaxAmountsIn.push(amount)
}
@ -1263,7 +1109,7 @@ export class Pool {
const tokens = await this.getFinalTokens(poolAddress)
for (let i = 0; i < 2; i++) {
const amount = await this.amountToUnits(tokens[i], minAmountsOut[i])
const amount = await amountToUnits(this.web3, tokens[i], minAmountsOut[i])
weiMinAmountsOut.push(amount)
}
let result = null
@ -1347,7 +1193,7 @@ export class Pool {
)
let result = null
const amountInFormatted = await this.amountToUnits(tokenIn, tokenAmountIn)
const amountInFormatted = await amountToUnits(this.web3, tokenIn, tokenAmountIn)
const estGas = await this.estJoinswapExternAmountIn(
account,
poolAddress,
@ -1434,7 +1280,7 @@ export class Pool {
)
let result = null
const maxAmountInFormatted = await this.amountToUnits(tokenIn, maxAmountIn)
const maxAmountInFormatted = await amountToUnits(this.web3, tokenIn, maxAmountIn)
const estGas = await this.estJoinswapPoolAmountOut(
account,
poolAddress,
@ -1520,7 +1366,11 @@ export class Pool {
)
let result = null
const minTokenOutFormatted = await this.amountToUnits(tokenOut, minTokenAmountOut)
const minTokenOutFormatted = await amountToUnits(
this.web3,
tokenOut,
minTokenAmountOut
)
const estGas = await this.estExitswapPoolAmountIn(
account,
poolAddress,
@ -1708,7 +1558,7 @@ export class Pool {
this.config
)
const amountOutFormatted = await this.amountToUnits(tokenOut, tokenAmountOut)
const amountOutFormatted = await amountToUnits(this.web3, tokenOut, tokenAmountOut)
let amount = null
@ -1721,7 +1571,7 @@ export class Pool {
this.web3.utils.toWei(swapMarketFee)
)
.call()
amount = await this.unitsToAmount(tokenIn, result)
amount = await unitsToAmount(this.web3, tokenIn, result)
} catch (e) {
this.logger.error('ERROR: Failed to calcInGivenOut')
}
@ -1740,7 +1590,7 @@ export class Pool {
this.config
)
const amountInFormatted = await this.amountToUnits(tokenIn, tokenAmountIn)
const amountInFormatted = await amountToUnits(this.web3, tokenIn, tokenAmountIn)
let amount = null
@ -1754,7 +1604,7 @@ export class Pool {
)
.call()
amount = await this.unitsToAmount(tokenOut, result)
amount = await unitsToAmount(this.web3, tokenOut, result)
} catch (e) {
this.logger.error('ERROR: Failed to calcOutGivenIn')
}
@ -1774,10 +1624,13 @@ export class Pool {
try {
const result = await pool.methods
.calcPoolOutSingleIn(tokenIn, await this.amountToUnits(tokenIn, tokenAmountIn))
.calcPoolOutSingleIn(
tokenIn,
await amountToUnits(this.web3, tokenIn, tokenAmountIn)
)
.call()
amount = await this.unitsToAmount(poolAddress, result)
amount = await unitsToAmount(this.web3, poolAddress, result)
} catch (e) {
this.logger.error(`ERROR: Failed to calculate PoolOutGivenSingleIn : ${e.message}`)
}
@ -1794,14 +1647,14 @@ export class Pool {
this.config
)
let amount = null
const amountFormatted = await this.amountToUnits(poolAddress, poolAmountOut)
const amountFormatted = await amountToUnits(this.web3, poolAddress, poolAmountOut)
try {
const result = await pool.methods
.calcSingleInPoolOut(tokenIn, amountFormatted)
.call()
amount = await this.unitsToAmount(tokenIn, result)
amount = await unitsToAmount(this.web3, tokenIn, result)
} catch (e) {
this.logger.error(`ERROR: Failed to calculate SingleInGivenPoolOut : ${e.message}`)
}
@ -1823,10 +1676,10 @@ export class Pool {
const result = await pool.methods
.calcSingleOutPoolIn(
tokenOut,
await this.amountToUnits(poolAddress, poolAmountIn)
await amountToUnits(this.web3, poolAddress, poolAmountIn)
)
.call()
amount = await this.unitsToAmount(tokenOut, result)
amount = await unitsToAmount(this.web3, tokenOut, result)
} catch (e) {
this.logger.error(`ERROR: Failed to calculate SingleOutGivenPoolIn : ${e}`)
}
@ -1846,10 +1699,13 @@ export class Pool {
try {
const result = await pool.methods
.calcPoolInSingleOut(tokenOut, await this.amountToUnits(tokenOut, tokenAmountOut))
.calcPoolInSingleOut(
tokenOut,
await amountToUnits(this.web3, tokenOut, tokenAmountOut)
)
.call()
amount = await this.unitsToAmount(poolAddress, result)
amount = await unitsToAmount(this.web3, poolAddress, result)
} catch (e) {
this.logger.error(`ERROR: Failed to calculate PoolInGivenSingleOut : ${e.message}`)
}

View File

@ -11,6 +11,7 @@ import {
import { noZeroX } from '../utils/ConversionTypeHelper'
import { signText, signWithHash } from '../utils/SignatureUtils'
import fetch from 'cross-fetch'
import { DownloadResponse } from '../@types/DownloadResponse'
export interface HttpCallback {
(httpMethod: string, url: string, body: string, header: any): Promise<any>
}
@ -567,12 +568,11 @@ export class Provider {
public async computeResult(
jobId: string,
index: number,
destination: string,
accountId: string,
providerUri: string,
web3: Web3,
signal?: AbortSignal
): Promise<any> {
): Promise<DownloadResponse | void> {
const providerEndpoints = await this.getEndpoints(providerUri)
const serviceEndpoints = await this.getServiceEndpoints(
providerUri,
@ -604,15 +604,16 @@ export class Provider {
if (!computeResultUrl) return null
try {
!destination
? await downloadFileBrowser(consumeUrl)
: await downloadFile(consumeUrl, destination, index)
if (document) {
await downloadFileBrowser(consumeUrl)
} else {
return await downloadFile(consumeUrl, index)
}
} catch (e) {
LoggerInstance.error('Error getting job result')
LoggerInstance.error(e)
throw e
}
return destination
}
/** Deletes a compute job.

View File

@ -1,5 +1,4 @@
import Config from '../models/Config'
import fs from 'fs'
// eslint-disable-next-line import/no-named-default
import { default as DefaultContractsAddresses } from '@oceanprotocol/contracts/addresses/address.json'
import LoggerInstance from './Logger'
@ -161,38 +160,13 @@ export const configHelperNetworks: Config[] = [
export class ConfigHelper {
/* Load contract addresses from env ADDRESS_FILE (generated by ocean-contracts) */
public getAddressesFromEnv(network: string): Partial<Config> {
public getAddressesFromEnv(network: string, customAddresses?: any): Partial<Config> {
// use the defaults first
let configAddresses: Partial<Config>
if (DefaultContractsAddresses[network]) {
const {
FixedPrice,
Dispenser,
Staking,
poolTemplate,
OPFCommunityFeeCollector,
ERC721Factory,
Ocean,
chainId,
startBlock
} = DefaultContractsAddresses[network]
configAddresses = {
erc721FactoryAddress: ERC721Factory,
sideStakingAddress: Staking,
opfCommunityFeeCollector: OPFCommunityFeeCollector,
poolTemplateAddress: poolTemplate,
fixedRateExchangeAddress: FixedPrice,
dispenserAddress: Dispenser,
oceanTokenAddress: Ocean,
chainId: chainId,
startBlock: startBlock,
...(process.env.AQUARIUS_URI && { metadataCacheUri: process.env.AQUARIUS_URI })
}
}
// try ADDRESS_FILE env
if (fs && process.env.ADDRESS_FILE) {
// load from custom addresses structure
if (customAddresses) {
try {
const data = JSON.parse(fs.readFileSync(process.env.ADDRESS_FILE, 'utf8'))
const {
FixedPrice,
Dispenser,
@ -203,7 +177,7 @@ export class ConfigHelper {
Ocean,
chainId,
startBlock
} = data[network]
} = customAddresses[network]
configAddresses = {
erc721FactoryAddress: ERC721Factory,
sideStakingAddress: Staking,
@ -220,6 +194,33 @@ export class ConfigHelper {
// console.error(`ERROR: Could not load local contract address file: ${e.message}`)
// return null
}
} else {
// no custom addresses structure was passed, trying to load default
if (DefaultContractsAddresses[network]) {
const {
FixedPrice,
Dispenser,
Staking,
poolTemplate,
OPFCommunityFeeCollector,
ERC721Factory,
Ocean,
chainId,
startBlock
} = DefaultContractsAddresses[network]
configAddresses = {
erc721FactoryAddress: ERC721Factory,
sideStakingAddress: Staking,
opfCommunityFeeCollector: OPFCommunityFeeCollector,
poolTemplateAddress: poolTemplate,
fixedRateExchangeAddress: FixedPrice,
dispenserAddress: Dispenser,
oceanTokenAddress: Ocean,
chainId: chainId,
startBlock: startBlock,
...(process.env.AQUARIUS_URI && { metadataCacheUri: process.env.AQUARIUS_URI })
}
}
}
return configAddresses
}

View File

@ -1 +1,2 @@
export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
export const GASLIMIT_DEFAULT = 1000000

View File

@ -4,6 +4,8 @@ import { Contract } from 'web3-eth-contract'
import { generateDtName } from './DatatokenName'
import { Erc20CreateParams, FreCreationParams, PoolCreationParams } from '../interfaces'
import { Config } from '../models'
import { AbiItem } from 'web3-utils/types'
import { minAbi } from './minAbi'
export function setContractDefaults(contract: Contract, config: Config): Contract {
if (config) {
@ -90,3 +92,40 @@ export function getPoolCreationParams(poolParams: PoolCreationParams): any {
swapFees: [poolParams.swapFeeLiquidityProvider, poolParams.swapFeeMarketRunner]
}
}
export async function unitsToAmount(
web3: Web3,
token: string,
amount: string
): Promise<string> {
try {
const tokenContract = new web3.eth.Contract(minAbi, token)
let decimals = await tokenContract.methods.decimals().call()
if (decimals === '0') {
decimals = 18
}
const amountFormatted = new BigNumber(parseInt(amount) / 10 ** decimals)
BigNumber.config({ EXPONENTIAL_AT: 50 })
return amountFormatted.toString()
} catch (e) {
this.logger.error('ERROR: FAILED TO CALL DECIMALS(), USING 18')
}
}
export async function amountToUnits(
web3: Web3,
token: string,
amount: string
): Promise<string> {
try {
const tokenContract = new web3.eth.Contract(minAbi, token)
let decimals = await tokenContract.methods.decimals().call()
if (decimals === '0') {
decimals = 18
}
const amountFormatted = new BigNumber(parseInt(amount) * 10 ** decimals)
BigNumber.config({ EXPONENTIAL_AT: 50 })
return amountFormatted.toString()
} catch (e) {
this.logger.error('ERROR: FAILED TO CALL DECIMALS(), USING 18')
}
}

View File

@ -1,7 +1,6 @@
import fetch from 'cross-fetch'
import LoggerInstance from './Logger'
import fs from 'fs'
import save from 'save-file'
import { DownloadResponse } from '../@types/DownloadResponse'
export async function fetchData(url: string, opts: RequestInit): Promise<Response> {
const result = await fetch(url, opts)
@ -22,9 +21,8 @@ export async function downloadFileBrowser(url: string): Promise<void> {
export async function downloadFile(
url: string,
destination?: string,
index?: number
): Promise<string> {
): Promise<DownloadResponse> {
const response = await fetch(url)
if (!response.ok) {
throw new Error('Response error.')
@ -41,14 +39,8 @@ export async function downloadFile(
filename = `file${index}`
}
}
if (destination) {
// eslint-disable-next-line no-async-promise-executor
fs.mkdirSync(destination, { recursive: true })
fs.writeFileSync(`${destination}/${filename}`, await response.text())
return destination
} else {
save(await response.arrayBuffer(), filename)
}
return { data: await response.arrayBuffer(), filename }
}
export async function getData(url: string): Promise<Response> {

126
src/utils/TokenUtils.ts Normal file
View File

@ -0,0 +1,126 @@
import Decimal from 'decimal.js'
import { Contract } from 'web3-eth-contract'
import { amountToUnits, getFairGasPrice, unitsToAmount } from './ContractUtils'
import { minAbi } from './minAbi'
import LoggerInstance from './Logger'
import { TransactionReceipt } from 'web3-core'
import Web3 from 'web3'
import { GASLIMIT_DEFAULT } from '.'
/**
* Estimate gas cost for approval function
* @param {String} account
* @param {String} tokenAddress
* @param {String} spender
* @param {String} amount
* @param {String} force
* @param {Contract} contractInstance optional contract instance
* @return {Promise<number>}
*/
export async function estApprove(
web3: Web3,
account: string,
tokenAddress: string,
spender: string,
amount: string,
contractInstance?: Contract
): Promise<number> {
const tokenContract = contractInstance || new web3.eth.Contract(minAbi, tokenAddress)
const gasLimitDefault = GASLIMIT_DEFAULT
let estGas
try {
estGas = await tokenContract.methods
.approve(spender, amount)
.estimateGas({ from: account }, (err, estGas) => (err ? gasLimitDefault : estGas))
} catch (e) {
estGas = gasLimitDefault
LoggerInstance.error('estimate gas failed for approve!', e)
}
return estGas
}
/**
* Approve spender to spent amount tokens
* @param {String} account
* @param {String} tokenAddress
* @param {String} spender
* @param {String} amount (always expressed as wei)
* @param {String} force if true, will overwrite any previous allowence. Else, will check if allowence is enough and will not send a transaction if it's not needed
*/
export async function approve(
web3: Web3,
account: string,
tokenAddress: string,
spender: string,
amount: string,
force = false
): Promise<TransactionReceipt | string> {
const tokenContract = new web3.eth.Contract(minAbi, tokenAddress)
if (!force) {
const currentAllowence = await allowance(web3, tokenAddress, account, spender)
if (new Decimal(currentAllowence).greaterThanOrEqualTo(new Decimal(amount))) {
return currentAllowence
}
}
let result = null
const amountFormatted = await amountToUnits(web3, tokenAddress, amount)
const estGas = await estApprove(
web3,
account,
tokenAddress,
spender,
amountFormatted,
tokenContract
)
try {
result = await tokenContract.methods.approve(spender, amountFormatted).send({
from: account,
gas: estGas + 1,
gasPrice: await getFairGasPrice(web3, null)
})
} catch (e) {
LoggerInstance.error(
`ERRPR: Failed to approve spender to spend tokens : ${e.message}`
)
}
return result
}
/**
* Get Allowance for any erc20
* @param {Web3} web3
* @param {String } tokenAdress
* @param {String} account
* @param {String} spender
*/
export async function allowance(
web3: Web3,
tokenAddress: string,
account: string,
spender: string
): Promise<string> {
const tokenContract = new web3.eth.Contract(minAbi, tokenAddress)
const trxReceipt = await tokenContract.methods.allowance(account, spender).call()
return await unitsToAmount(web3, tokenAddress, trxReceipt)
}
/**
* Get balance for any erc20
* @param {Web3} web3
* @param {String} tokenAdress
* @param {String} owner
* @param {String} spender
*/
export async function balance(
web3: Web3,
tokenAddress: string,
account: string
): Promise<string> {
const tokenContract = new web3.eth.Contract(minAbi, tokenAddress)
const trxReceipt = await tokenContract.methods.balanceOf(account).call()
return await unitsToAmount(web3, tokenAddress, trxReceipt)
}

View File

@ -6,3 +6,4 @@ export * from './ConfigHelper'
export * from './DdoHelpers'
export * from './Constants'
export * from './SignatureUtils'
export * from './TokenUtils'

224
src/utils/minAbi.ts Normal file
View File

@ -0,0 +1,224 @@
import { AbiItem } from 'web3-utils/types'
export const minAbi = [
{
constant: true,
inputs: [],
name: 'name',
outputs: [
{
name: '',
type: 'string'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{
name: '_spender',
type: 'address'
},
{
name: '_value',
type: 'uint256'
}
],
name: 'approve',
outputs: [
{
name: '',
type: 'bool'
}
],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'totalSupply',
outputs: [
{
name: '',
type: 'uint256'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{
name: '_from',
type: 'address'
},
{
name: '_to',
type: 'address'
},
{
name: '_value',
type: 'uint256'
}
],
name: 'transferFrom',
outputs: [
{
name: '',
type: 'bool'
}
],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'decimals',
outputs: [
{
name: '',
type: 'uint8'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [
{
name: '_owner',
type: 'address'
}
],
name: 'balanceOf',
outputs: [
{
name: 'balance',
type: 'uint256'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'symbol',
outputs: [
{
name: '',
type: 'string'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{
name: '_to',
type: 'address'
},
{
name: '_value',
type: 'uint256'
}
],
name: 'transfer',
outputs: [
{
name: '',
type: 'bool'
}
],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [
{
name: '_owner',
type: 'address'
},
{
name: '_spender',
type: 'address'
}
],
name: 'allowance',
outputs: [
{
name: '',
type: 'uint256'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
payable: true,
stateMutability: 'payable',
type: 'fallback'
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: 'owner',
type: 'address'
},
{
indexed: true,
name: 'spender',
type: 'address'
},
{
indexed: false,
name: 'value',
type: 'uint256'
}
],
name: 'Approval',
type: 'event'
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: 'from',
type: 'address'
},
{
indexed: true,
name: 'to',
type: 'address'
},
{
indexed: false,
name: 'value',
type: 'uint256'
}
],
name: 'Transfer',
type: 'event'
}
] as AbiItem[]

View File

@ -8,10 +8,9 @@ import { Erc20CreateParams } from '../../src/interfaces'
import { getHash } from '../../src/utils'
import { Nft } from '../../src/tokens/NFT'
import Web3 from 'web3'
import { algo, SHA256 } from 'crypto-js'
import { SHA256 } from 'crypto-js'
import { homedir } from 'os'
import fs from 'fs'
import { downloadFile } from '../../src/utils/FetchHelper'
import console from 'console'
import { ProviderFees } from '../../src/@types'
@ -179,7 +178,6 @@ describe('Simple compute tests', async () => {
encryptedResponse,
'0x' + metadataHash
)
console.log('setMetadata tx', res)
// let's publish the algorithm as well
const nftParamsAlgo: NftCreateData = {
name: 'testNFT',
@ -229,7 +227,6 @@ describe('Simple compute tests', async () => {
'0x' + metadataHash
)
console.log('starting to wait for aqua')
// let's wait
const resolvedDDOAsset = await aquarius.waitForAqua(ddo.id)
assert(resolvedDDOAsset, 'Cannot fetch DDO from Aquarius')

View File

@ -11,7 +11,6 @@ import { SHA256 } from 'crypto-js'
import { homedir } from 'os'
import fs from 'fs'
import { downloadFile } from '../../src/utils/FetchHelper'
import console from 'console'
import { ProviderFees } from '../../src/@types/Provider'
const data = JSON.parse(
@ -23,7 +22,6 @@ const data = JSON.parse(
)
const addresses = data.development
console.log(addresses)
const aquarius = new Aquarius('http://127.0.0.1:5000')
const web3 = new Web3('http://127.0.0.1:8545')
const providerUrl = 'http://172.15.0.4:8030'
@ -161,7 +159,7 @@ describe('Simple Publish & consume test', async () => {
)
assert(downloadURL, 'Provider getDownloadUrl failed')
try {
await downloadFile(downloadURL, './tmpfile')
const fileData = await downloadFile(downloadURL)
} catch (e) {
assert.fail('Download failed')
}

View File

@ -411,7 +411,6 @@ describe('Nft Factory test', () => {
_providerFees: providerFees
}
]
console.log('orders', orders)
await nftFactory.startMultipleTokenOrder(user2, orders)
// we check user2 has no more DTs
expect(await dtContract.methods.balanceOf(user2).call()).to.equal('0')

View File

@ -12,7 +12,7 @@ import Dispenser from '@oceanprotocol/contracts/artifacts/contracts/pools/dispen
import FixedRate from '@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json'
import PoolTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BPool.sol/BPool.json'
import OPFCollector from '@oceanprotocol/contracts/artifacts/contracts/communityFee/OPFCommunityFeeCollector.sol/OPFCommunityFeeCollector.json'
import { LoggerInstance } from '../../../../src/utils'
import { allowance, amountToUnits, approve, LoggerInstance } from '../../../../src/utils'
import { NftFactory, NftCreateData } from '../../../../src/factories/NFTFactory'
import { Pool } from '../../../../src/pools/balancer/Pool'
import {
@ -86,27 +86,31 @@ describe('Pool unit test', () => {
contracts.MockERC20.options.jsonInterface,
contracts.usdcAddress
)
await pool.approve(
await approve(
web3,
contracts.accounts[0],
contracts.daiAddress,
contracts.factory721Address,
'2000'
)
await pool.approve(
await approve(
web3,
contracts.accounts[0],
contracts.usdcAddress,
contracts.factory721Address,
'10000'
)
expect(
await pool.allowance(
await allowance(
web3,
contracts.daiAddress,
contracts.accounts[0],
contracts.factory721Address
)
).to.equal('2000')
expect(
await pool.allowance(
await allowance(
web3,
contracts.usdcAddress,
contracts.accounts[0],
contracts.factory721Address
@ -116,7 +120,7 @@ describe('Pool unit test', () => {
web3.utils.toWei('100000')
)
await pool.amountToUnits(contracts.usdcAddress, '20')
await amountToUnits(web3, contracts.usdcAddress, '20')
})
describe('Test a pool with DAI (18 Decimals)', () => {
@ -142,7 +146,7 @@ describe('Pool unit test', () => {
symbol: 'ERC20DT1Symbol'
}
const baseTokenInitialLiq = await pool.amountToUnits(contracts.daiAddress, '2000')
const baseTokenInitialLiq = await amountToUnits(web3, contracts.daiAddress, '2000')
const poolParams: PoolCreationParams = {
ssContract: contracts.sideStakingAddress,
@ -270,7 +274,7 @@ describe('Pool unit test', () => {
web3.utils.toWei('1000')
)
expect(await erc20Contract.methods.balanceOf(user2).call()).to.equal('0')
await pool.approve(user2, contracts.daiAddress, poolAddress, '10')
await approve(web3, user2, contracts.daiAddress, poolAddress, '10')
const tokenInOutMarket: TokenInOutMarket = {
tokenIn: contracts.daiAddress,
@ -294,7 +298,7 @@ describe('Pool unit test', () => {
})
it('#swapExactAmountOut - should swap', async () => {
await pool.approve(user2, contracts.daiAddress, poolAddress, '100')
await approve(web3, user2, contracts.daiAddress, poolAddress, '100')
expect(await daiContract.methods.balanceOf(user2).call()).to.equal(
web3.utils.toWei('990')
)
@ -324,8 +328,8 @@ describe('Pool unit test', () => {
'50' // Amounts IN
]
await pool.approve(user2, erc20Token, poolAddress, '50')
await pool.approve(user2, contracts.daiAddress, poolAddress, '50')
await approve(web3, user2, erc20Token, poolAddress, '50')
await approve(web3, user2, contracts.daiAddress, poolAddress, '50')
const tx = await pool.joinPool(user2, poolAddress, BPTAmountOut, maxAmountsIn)
assert(tx != null)
expect(await pool.sharesBalance(user2, poolAddress)).to.equal(BPTAmountOut)
@ -335,8 +339,8 @@ describe('Pool unit test', () => {
it('#joinswapExternAmountIn- user2 should add liquidity, receiving LP tokens', async () => {
const daiAmountIn = '100'
const minBPTOut = '0.1'
await pool.approve(user2, contracts.daiAddress, poolAddress, '100', true)
expect(await pool.allowance(contracts.daiAddress, user2, poolAddress)).to.equal(
await approve(web3, user2, contracts.daiAddress, poolAddress, '100', true)
expect(await allowance(web3, contracts.daiAddress, user2, poolAddress)).to.equal(
'100'
)
const tx = await pool.joinswapExternAmountIn(
@ -361,7 +365,7 @@ describe('Pool unit test', () => {
const BPTAmountOut = '0.1'
const maxDAIIn = '100'
await pool.approve(user2, contracts.daiAddress, poolAddress, '100')
await approve(web3, user2, contracts.daiAddress, poolAddress, '100')
const tx = await pool.joinswapPoolAmountOut(
user2,
@ -627,7 +631,7 @@ describe('Pool unit test', () => {
vestingAmount: '10000',
vestedBlocks: 2500000,
initialBaseTokenLiquidity: web3.utils.fromWei(
await pool.amountToUnits(contracts.usdcAddress, '2000')
await amountToUnits(web3, contracts.usdcAddress, '2000')
),
swapFeeLiquidityProvider: 1e15,
swapFeeMarketRunner: 1e15
@ -807,7 +811,7 @@ describe('Pool unit test', () => {
})
it('#swapExactAmountIn - should swap', async () => {
const transferAmount = await pool.amountToUnits(contracts.usdcAddress, '1000') // 1000 USDC
const transferAmount = await amountToUnits(web3, contracts.usdcAddress, '1000') // 1000 USDC
await usdcContract.methods
.transfer(user2, transferAmount)
.send({ from: contracts.accounts[0] })
@ -816,7 +820,7 @@ describe('Pool unit test', () => {
)
expect(await erc20Contract.methods.balanceOf(user2).call()).to.equal('0')
await pool.approve(user2, contracts.usdcAddress, poolAddress, '10')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '10')
const tokenInOutMarket: TokenInOutMarket = {
tokenIn: contracts.usdcAddress,
tokenOut: erc20Token,
@ -840,9 +844,9 @@ describe('Pool unit test', () => {
it('#swapExactAmountOut - should swap', async () => {
expect(await usdcContract.methods.balanceOf(user2).call()).to.equal(
(await pool.amountToUnits(contracts.usdcAddress, '990')).toString()
(await amountToUnits(web3, contracts.usdcAddress, '990')).toString()
)
await pool.approve(user2, contracts.usdcAddress, poolAddress, '100')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '100')
const tokenInOutMarket: TokenInOutMarket = {
tokenIn: contracts.usdcAddress,
tokenOut: erc20Token,
@ -870,8 +874,8 @@ describe('Pool unit test', () => {
'50' // Amounts IN
]
await pool.approve(user2, erc20Token, poolAddress, '50')
await pool.approve(user2, contracts.usdcAddress, poolAddress, '50')
await approve(web3, user2, erc20Token, poolAddress, '50')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '50')
const tx = await pool.joinPool(user2, poolAddress, BPTAmountOut, maxAmountsIn)
assert(tx != null)
expect(await pool.sharesBalance(user2, poolAddress)).to.equal(BPTAmountOut)
@ -885,7 +889,7 @@ describe('Pool unit test', () => {
it('#joinswapExternAmountIn- user2 should add liquidity, receiving LP tokens', async () => {
const usdcAmountIn = '100'
const minBPTOut = '0.1'
await pool.approve(user2, contracts.usdcAddress, poolAddress, '100', true)
await approve(web3, user2, contracts.usdcAddress, poolAddress, '100', true)
const tx = await pool.joinswapExternAmountIn(
user2,
@ -909,7 +913,7 @@ describe('Pool unit test', () => {
const BPTAmountOut = '0.1'
const maxUSDCIn = '100'
await pool.approve(user2, contracts.usdcAddress, poolAddress, '100')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '100')
const tx = await pool.joinswapPoolAmountOut(
user2,

View File

@ -86,11 +86,6 @@ describe('Fixed Rate unit test', () => {
contracts.MockERC20.options.jsonInterface,
contracts.usdcAddress
)
console.log(
await usdcContract.methods.decimals().call(),
'USDC DECIMALS IN THIS TEST'
)
})
describe('Test a Fixed Rate Exchange with DAI (18 Decimals)', () => {

View File

@ -12,7 +12,7 @@ import Dispenser from '@oceanprotocol/contracts/artifacts/contracts/pools/dispen
import FixedRate from '@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json'
import PoolTemplate from '@oceanprotocol/contracts/artifacts/contracts/pools/balancer/BPool.sol/BPool.json'
import OPFCollector from '@oceanprotocol/contracts/artifacts/contracts/communityFee/OPFCommunityFeeCollector.sol/OPFCommunityFeeCollector.json'
import { LoggerInstance } from '../../../../src/utils'
import { allowance, amountToUnits, approve, LoggerInstance } from '../../../../src/utils'
import { NftFactory, NftCreateData } from '../../../../src/factories/NFTFactory'
import { Pool } from '../../../../src/pools/balancer/Pool'
import { SideStaking } from '../../../../src/pools/ssContracts/SideStaking'
@ -93,13 +93,15 @@ describe('SideStaking unit test', () => {
contracts.MockERC20.options.jsonInterface,
contracts.usdcAddress
)
await pool.approve(
await approve(
web3,
contracts.accounts[0],
contracts.daiAddress,
contracts.factory721Address,
'2000'
)
await pool.approve(
await approve(
web3,
contracts.accounts[0],
contracts.usdcAddress,
contracts.factory721Address,
@ -107,14 +109,16 @@ describe('SideStaking unit test', () => {
)
expect(
await pool.allowance(
await allowance(
web3,
contracts.daiAddress,
contracts.accounts[0],
contracts.factory721Address
)
).to.equal('2000')
expect(
await pool.allowance(
await allowance(
web3,
contracts.usdcAddress,
contracts.accounts[0],
contracts.factory721Address
@ -129,7 +133,7 @@ describe('SideStaking unit test', () => {
'USDC DECIMALS IN THIS TEST'
)
await pool.amountToUnits(contracts.usdcAddress, '20')
await amountToUnits(web3, contracts.usdcAddress, '20')
})
describe('Test a pool with DAI (18 Decimals)', () => {
@ -291,7 +295,7 @@ describe('SideStaking unit test', () => {
web3.utils.toWei('1000')
)
expect(await erc20Contract.methods.balanceOf(user2).call()).to.equal('0')
await pool.approve(user2, contracts.daiAddress, poolAddress, '10')
await approve(web3, user2, contracts.daiAddress, poolAddress, '10')
const tokenInOutMarket: TokenInOutMarket = {
tokenIn: contracts.daiAddress,
tokenOut: erc20Token,
@ -315,7 +319,7 @@ describe('SideStaking unit test', () => {
})
it('#swapExactAmountOut - should swap', async () => {
await pool.approve(user2, contracts.daiAddress, poolAddress, '100')
await approve(web3, user2, contracts.daiAddress, poolAddress, '100')
expect(await daiContract.methods.balanceOf(user2).call()).to.equal(
web3.utils.toWei('990')
)
@ -341,8 +345,8 @@ describe('SideStaking unit test', () => {
it('#joinswapExternAmountIn- user2 should add liquidity, receiving LP tokens', async () => {
const daiAmountIn = '100'
const minBPTOut = '0.1'
await pool.approve(user2, contracts.daiAddress, poolAddress, '100', true)
expect(await pool.allowance(contracts.daiAddress, user2, poolAddress)).to.equal(
await approve(web3, user2, contracts.daiAddress, poolAddress, '100', true)
expect(await allowance(web3, contracts.daiAddress, user2, poolAddress)).to.equal(
'100'
)
const tx = await pool.joinswapExternAmountIn(
@ -367,7 +371,7 @@ describe('SideStaking unit test', () => {
const BPTAmountOut = '0.1'
const maxDAIIn = '100'
await pool.approve(user2, contracts.daiAddress, poolAddress, '100')
await approve(web3, user2, contracts.daiAddress, poolAddress, '100')
const tx = await pool.joinswapPoolAmountOut(
user2,
@ -465,7 +469,7 @@ describe('SideStaking unit test', () => {
vestingAmount: '10000',
vestedBlocks: 2500000,
initialBaseTokenLiquidity: web3.utils.fromWei(
await pool.amountToUnits(contracts.usdcAddress, '2000')
await amountToUnits(web3, contracts.usdcAddress, '2000')
),
swapFeeLiquidityProvider: 1e15,
swapFeeMarketRunner: 1e15
@ -544,7 +548,7 @@ describe('SideStaking unit test', () => {
})
it('#swapExactAmountIn - should swap', async () => {
const transferAmount = await pool.amountToUnits(contracts.usdcAddress, '1000') // 1000 USDC
const transferAmount = await amountToUnits(web3, contracts.usdcAddress, '1000') // 1000 USDC
await usdcContract.methods
.transfer(user2, transferAmount)
.send({ from: contracts.accounts[0] })
@ -553,7 +557,7 @@ describe('SideStaking unit test', () => {
)
expect(await erc20Contract.methods.balanceOf(user2).call()).to.equal('0')
await pool.approve(user2, contracts.usdcAddress, poolAddress, '10')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '10')
const tokenInOutMarket: TokenInOutMarket = {
tokenIn: contracts.usdcAddress,
tokenOut: erc20Token,
@ -577,9 +581,9 @@ describe('SideStaking unit test', () => {
it('#swapExactAmountOut - should swap', async () => {
expect(await usdcContract.methods.balanceOf(user2).call()).to.equal(
(await pool.amountToUnits(contracts.usdcAddress, '990')).toString()
(await amountToUnits(web3, contracts.usdcAddress, '990')).toString()
)
await pool.approve(user2, contracts.usdcAddress, poolAddress, '100')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '100')
const tokenInOutMarket: TokenInOutMarket = {
tokenIn: contracts.usdcAddress,
tokenOut: erc20Token,
@ -603,7 +607,7 @@ describe('SideStaking unit test', () => {
it('#joinswapExternAmountIn- user2 should add liquidity, receiving LP tokens', async () => {
const usdcAmountIn = '100'
const minBPTOut = '0.1'
await pool.approve(user2, contracts.usdcAddress, poolAddress, '100', true)
await approve(web3, user2, contracts.usdcAddress, poolAddress, '100', true)
const tx = await pool.joinswapExternAmountIn(
user2,
@ -627,7 +631,7 @@ describe('SideStaking unit test', () => {
const BPTAmountOut = '0.1'
const maxUSDCIn = '100'
await pool.approve(user2, contracts.usdcAddress, poolAddress, '100')
await approve(web3, user2, contracts.usdcAddress, poolAddress, '100')
const tx = await pool.joinswapPoolAmountOut(
user2,