diff --git a/src/contracts/SmartContract.ts b/src/contracts/SmartContract.ts new file mode 100644 index 00000000..fb3114a0 --- /dev/null +++ b/src/contracts/SmartContract.ts @@ -0,0 +1,46 @@ +import Web3 from 'web3' +import { AbiItem } from 'web3-utils' +import { Config, ConfigHelper } from '../config' +import { amountToUnits, unitsToAmount } from '../utils' + +export abstract class SmartContract { + public web3: Web3 + public config: Config + public abi: AbiItem | AbiItem[] + + abstract getDefaultAbi(): AbiItem | AbiItem[] + + /** + * Instantiate the smart contract. + * @param {Web3} web3 + * @param {string | number} network Network id or name + * @param {Config} config Configutation of the smart contract + * @param {AbiItem | AbiItem[]} abi ABI of the smart contract + */ + constructor( + web3: Web3, + network?: string | number, + config?: Config, + abi?: AbiItem | AbiItem[] + ) { + this.web3 = web3 + this.config = config || new ConfigHelper().getConfig(network || 'unknown') + this.abi = abi || (this.getDefaultAbi() as AbiItem[]) + } + + async amountToUnits( + token: string, + amount: string, + tokenDecimals?: number + ): Promise { + return amountToUnits(this.web3, token, amount, tokenDecimals) + } + + async unitsToAmount( + token: string, + amount: string, + tokenDecimals?: number + ): Promise { + return unitsToAmount(this.web3, token, amount, tokenDecimals) + } +} diff --git a/src/contracts/SmartContractWithAddress.ts b/src/contracts/SmartContractWithAddress.ts new file mode 100644 index 00000000..a1f56392 --- /dev/null +++ b/src/contracts/SmartContractWithAddress.ts @@ -0,0 +1,34 @@ +import Web3 from 'web3' +import { Contract } from 'web3-eth-contract' +import { AbiItem } from 'web3-utils' +import { Config } from '../config' +import { setContractDefaults } from '../utils' +import { SmartContract } from '.' + +export abstract class SmartContractWithAddress extends SmartContract { + public address: string + public contract: Contract + + /** + * Instantiate the smart contract. + * @param {string} address Address of the smart contract + * @param {Web3} web3 + * @param {string | number} network Network id or name + * @param {Config} config Configutation of the smart contract + * @param {AbiItem | AbiItem[]} abi ABI of the smart contract + */ + constructor( + address: string, + web3: Web3, + network?: string | number, + config?: Config, + abi?: AbiItem | AbiItem[] + ) { + super(web3, network, config, abi) + this.address = address + this.contract = setContractDefaults( + new this.web3.eth.Contract(this.getDefaultAbi(), this.address), + this.config + ) + } +} diff --git a/src/contracts/index.ts b/src/contracts/index.ts index bef542cb..3d516a73 100644 --- a/src/contracts/index.ts +++ b/src/contracts/index.ts @@ -1,3 +1,5 @@ +export * from './SmartContract' +export * from './SmartContractWithAddress' export * from './factories/NFTFactory' export * from './pools/Dispenser' export * from './pools/FixedRateExchange'