From 6686443317dcb30f6737d695d2e8d298a942eb8e Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 09:52:31 +0200 Subject: Implement ERC20Wrapper and it's first method getBalanceAsync --- src/0x.js.ts | 3 +++ src/contract_wrappers/erc20_wrapper.ts | 28 ++++++++++++++++++++++++++++ src/types.ts | 6 ++++++ 3 files changed, 37 insertions(+) create mode 100644 src/contract_wrappers/erc20_wrapper.ts diff --git a/src/0x.js.ts b/src/0x.js.ts index 7e48bc0a5..7932559fb 100644 --- a/src/0x.js.ts +++ b/src/0x.js.ts @@ -13,6 +13,7 @@ import compareVersions = require('compare-versions'); import {ExchangeWrapper} from './contract_wrappers/exchange_wrapper'; import {TokenRegistryWrapper} from './contract_wrappers/token_registry_wrapper'; import {ecSignatureSchema} from './schemas/ec_signature_schema'; +import {ERC20Wrapper} from './contract_wrappers/erc20_wrapper'; import {SolidityTypes, ECSignature, ZeroExError} from './types'; const MAX_DIGITS_IN_UNSIGNED_256_INT = 78; @@ -21,6 +22,7 @@ export class ZeroEx { public web3Wrapper: Web3Wrapper; public exchange: ExchangeWrapper; public tokenRegistry: TokenRegistryWrapper; + public erc20: ERC20Wrapper; /** * Computes the orderHash given the order parameters and returns it as a hex encoded string. */ @@ -135,6 +137,7 @@ export class ZeroEx { this.web3Wrapper = new Web3Wrapper(web3); this.exchange = new ExchangeWrapper(this.web3Wrapper); this.tokenRegistry = new TokenRegistryWrapper(this.web3Wrapper); + this.erc20 = new ERC20Wrapper(this.web3Wrapper); } /** * Signs an orderHash and returns it's elliptic curve signature diff --git a/src/contract_wrappers/erc20_wrapper.ts b/src/contract_wrappers/erc20_wrapper.ts new file mode 100644 index 000000000..60b1887db --- /dev/null +++ b/src/contract_wrappers/erc20_wrapper.ts @@ -0,0 +1,28 @@ +import * as _ from 'lodash'; +import * as BigNumber from 'bignumber.js'; +import {Web3Wrapper} from '../web3_wrapper'; +import {assert} from '../utils/assert'; +import {ContractWrapper} from './contract_wrapper'; +import * as TokenArtifacts from '../artifacts/Token.json'; +import {ERC20Contract} from '../types'; + +export class ERC20Wrapper extends ContractWrapper { + constructor(web3Wrapper: Web3Wrapper) { + super(web3Wrapper); + } + /** + * Returns an owner's ERC20 token balance + */ + public async getBalanceAsync(tokenAddress: string, ownerAddress: string): Promise { + assert.isETHAddressHex('ownerAddress', ownerAddress); + assert.isETHAddressHex('tokenAddress', tokenAddress); + + const contractInstance = await this.instantiateContractIfExistsAsync((TokenArtifacts as any), tokenAddress); + const tokenContract = contractInstance as ERC20Contract; + let balance = await tokenContract.balanceOf.call(ownerAddress); + // The BigNumber instance returned by Web3 is of a much older version then our own, we therefore + // should always re-instantiate the returned BigNumber after retrieval. + balance = _.isUndefined(balance) ? new BigNumber(0) : new BigNumber(balance); + return balance; + } +} diff --git a/src/types.ts b/src/types.ts index 273389480..f5b0f3e7c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -30,6 +30,12 @@ export interface ExchangeContract { isValidSignature: any; } +export interface ERC20Contract { + balanceOf: { + call: (address: string) => Promise; + }; +} + export interface TokenRegistryContract { getTokenMetaData: any; getTokenAddresses: any; -- cgit From 132b5d4f9b3bcb0d3f1a23790d54a4db173ca989 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 09:52:47 +0200 Subject: Add tests for getBalanceAsync --- test/erc20_wrapper_test.ts | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 test/erc20_wrapper_test.ts diff --git a/test/erc20_wrapper_test.ts b/test/erc20_wrapper_test.ts new file mode 100644 index 000000000..c28c057a7 --- /dev/null +++ b/test/erc20_wrapper_test.ts @@ -0,0 +1,55 @@ +import 'mocha'; +import * as chai from 'chai'; +import chaiAsPromised = require('chai-as-promised'); +import * as Web3 from 'web3'; +import * as BigNumber from 'bignumber.js'; +import promisify = require('es6-promisify'); +import {web3Factory} from './utils/web3_factory'; +import {ZeroEx} from '../src/0x.js'; +import {ZeroExError, Token} from '../src/types'; +import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; + +const expect = chai.expect; +chai.use(chaiAsPromised); +const blockchainLifecycle = new BlockchainLifecycle(); + +describe('ERC20Wrapper', () => { + let web3: Web3; + let zeroEx: ZeroEx; + let userAddresses: string[]; + let tokens: Token[]; + before(async () => { + web3 = web3Factory.create(); + zeroEx = new ZeroEx(web3); + userAddresses = await promisify(web3.eth.getAccounts)(); + tokens = await zeroEx.tokenRegistry.getTokensAsync(); + }); + beforeEach(async () => { + await blockchainLifecycle.startAsync(); + }); + afterEach(async () => { + await blockchainLifecycle.revertAsync(); + }); + describe('#getBalanceAsync', () => { + it('should return the balance for an existing ERC20 token', async () => { + const aToken = tokens[0]; + const aOwnerAddress = userAddresses[0]; + const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aOwnerAddress); + const expectedBalance = new BigNumber('100000000000000000000000000'); + expect(balance).to.be.bignumber.equal(expectedBalance); + }); + it ('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { + const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; + const aOwnerAddress = userAddresses[0]; + expect(zeroEx.erc20.getBalanceAsync(nonExistentTokenAddress, aOwnerAddress)) + .to.be.rejectedWith(ZeroExError.CONTRACT_DOES_NOT_EXIST); + }); + it ('should return a balance of 0 for a non-existent owner address', async () => { + const aToken = tokens[0]; + const aNonExistentOwner = '0x198C6Ad858F213Fb31b6FE809E25040E6B964593'; + const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aNonExistentOwner); + const expectedBalance = new BigNumber('0'); + expect(balance).to.be.bignumber.equal(expectedBalance); + }); + }); +}); -- cgit From 2c3b718a4fa063277163e72f1be962dab3dfd21a Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 14:48:41 +0200 Subject: rename erc20Wrapper to tokenWrapper to be more generic in case we end up supporting another spec --- src/0x.js.ts | 17 ++++++++--- src/contract_wrappers/erc20_wrapper.ts | 28 ----------------- src/contract_wrappers/token_wrapper.ts | 42 ++++++++++++++++++++++++++ test/erc20_wrapper_test.ts | 55 ---------------------------------- test/token_wrapper_test.ts | 55 ++++++++++++++++++++++++++++++++++ 5 files changed, 110 insertions(+), 87 deletions(-) delete mode 100644 src/contract_wrappers/erc20_wrapper.ts create mode 100644 src/contract_wrappers/token_wrapper.ts delete mode 100644 test/erc20_wrapper_test.ts create mode 100644 test/token_wrapper_test.ts diff --git a/src/0x.js.ts b/src/0x.js.ts index 7932559fb..96b290439 100644 --- a/src/0x.js.ts +++ b/src/0x.js.ts @@ -13,16 +13,16 @@ import compareVersions = require('compare-versions'); import {ExchangeWrapper} from './contract_wrappers/exchange_wrapper'; import {TokenRegistryWrapper} from './contract_wrappers/token_registry_wrapper'; import {ecSignatureSchema} from './schemas/ec_signature_schema'; -import {ERC20Wrapper} from './contract_wrappers/erc20_wrapper'; +import {TokenWrapper} from './contract_wrappers/token_wrapper'; import {SolidityTypes, ECSignature, ZeroExError} from './types'; const MAX_DIGITS_IN_UNSIGNED_256_INT = 78; export class ZeroEx { - public web3Wrapper: Web3Wrapper; public exchange: ExchangeWrapper; public tokenRegistry: TokenRegistryWrapper; - public erc20: ERC20Wrapper; + public erc20: TokenWrapper; + private web3Wrapper: Web3Wrapper; /** * Computes the orderHash given the order parameters and returns it as a hex encoded string. */ @@ -137,7 +137,16 @@ export class ZeroEx { this.web3Wrapper = new Web3Wrapper(web3); this.exchange = new ExchangeWrapper(this.web3Wrapper); this.tokenRegistry = new TokenRegistryWrapper(this.web3Wrapper); - this.erc20 = new ERC20Wrapper(this.web3Wrapper); + this.erc20 = new TokenWrapper(this.web3Wrapper); + } + /** + * Sets a new provider for the web3 instance used by 0x.js + */ + public setProvider(provider: Web3.Provider) { + this.web3Wrapper.setProvider(provider); + this.exchange.invalidateContractInstance(); + this.tokenRegistry.invalidateContractInstance(); + this.erc20.invalidateContractInstances(); } /** * Signs an orderHash and returns it's elliptic curve signature diff --git a/src/contract_wrappers/erc20_wrapper.ts b/src/contract_wrappers/erc20_wrapper.ts deleted file mode 100644 index 60b1887db..000000000 --- a/src/contract_wrappers/erc20_wrapper.ts +++ /dev/null @@ -1,28 +0,0 @@ -import * as _ from 'lodash'; -import * as BigNumber from 'bignumber.js'; -import {Web3Wrapper} from '../web3_wrapper'; -import {assert} from '../utils/assert'; -import {ContractWrapper} from './contract_wrapper'; -import * as TokenArtifacts from '../artifacts/Token.json'; -import {ERC20Contract} from '../types'; - -export class ERC20Wrapper extends ContractWrapper { - constructor(web3Wrapper: Web3Wrapper) { - super(web3Wrapper); - } - /** - * Returns an owner's ERC20 token balance - */ - public async getBalanceAsync(tokenAddress: string, ownerAddress: string): Promise { - assert.isETHAddressHex('ownerAddress', ownerAddress); - assert.isETHAddressHex('tokenAddress', tokenAddress); - - const contractInstance = await this.instantiateContractIfExistsAsync((TokenArtifacts as any), tokenAddress); - const tokenContract = contractInstance as ERC20Contract; - let balance = await tokenContract.balanceOf.call(ownerAddress); - // The BigNumber instance returned by Web3 is of a much older version then our own, we therefore - // should always re-instantiate the returned BigNumber after retrieval. - balance = _.isUndefined(balance) ? new BigNumber(0) : new BigNumber(balance); - return balance; - } -} diff --git a/src/contract_wrappers/token_wrapper.ts b/src/contract_wrappers/token_wrapper.ts new file mode 100644 index 000000000..bd815554a --- /dev/null +++ b/src/contract_wrappers/token_wrapper.ts @@ -0,0 +1,42 @@ +import * as _ from 'lodash'; +import * as BigNumber from 'bignumber.js'; +import {Web3Wrapper} from '../web3_wrapper'; +import {assert} from '../utils/assert'; +import {ContractWrapper} from './contract_wrapper'; +import * as TokenArtifacts from '../artifacts/Token.json'; +import {ERC20Contract} from '../types'; + +export class TokenWrapper extends ContractWrapper { + private tokenContractsByAddress: {[address: string]: ERC20Contract}; + constructor(web3Wrapper: Web3Wrapper) { + super(web3Wrapper); + this.tokenContractsByAddress = {}; + } + public invalidateContractInstances() { + this.tokenContractsByAddress = {}; + } + /** + * Returns an owner's ERC20 token balance + */ + public async getBalanceAsync(tokenAddress: string, ownerAddress: string): Promise { + assert.isETHAddressHex('ownerAddress', ownerAddress); + assert.isETHAddressHex('tokenAddress', tokenAddress); + + const tokenContract = await this.getTokenContractAsync(tokenAddress); + let balance = await tokenContract.balanceOf.call(ownerAddress); + // The BigNumber instance returned by Web3 is of a much older version then our own, we therefore + // should always re-instantiate the returned BigNumber after retrieval. + balance = _.isUndefined(balance) ? new BigNumber(0) : new BigNumber(balance); + return balance; + } + private async getTokenContractAsync(tokenAddress: string): Promise { + let tokenContract = this.tokenContractsByAddress[tokenAddress]; + if (!_.isUndefined(tokenContract)) { + return tokenContract; + } + const contractInstance = await this.instantiateContractIfExistsAsync((TokenArtifacts as any), tokenAddress); + tokenContract = contractInstance as ERC20Contract; + this.tokenContractsByAddress[tokenAddress] = tokenContract; + return tokenContract; + } +} diff --git a/test/erc20_wrapper_test.ts b/test/erc20_wrapper_test.ts deleted file mode 100644 index c28c057a7..000000000 --- a/test/erc20_wrapper_test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import 'mocha'; -import * as chai from 'chai'; -import chaiAsPromised = require('chai-as-promised'); -import * as Web3 from 'web3'; -import * as BigNumber from 'bignumber.js'; -import promisify = require('es6-promisify'); -import {web3Factory} from './utils/web3_factory'; -import {ZeroEx} from '../src/0x.js'; -import {ZeroExError, Token} from '../src/types'; -import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; - -const expect = chai.expect; -chai.use(chaiAsPromised); -const blockchainLifecycle = new BlockchainLifecycle(); - -describe('ERC20Wrapper', () => { - let web3: Web3; - let zeroEx: ZeroEx; - let userAddresses: string[]; - let tokens: Token[]; - before(async () => { - web3 = web3Factory.create(); - zeroEx = new ZeroEx(web3); - userAddresses = await promisify(web3.eth.getAccounts)(); - tokens = await zeroEx.tokenRegistry.getTokensAsync(); - }); - beforeEach(async () => { - await blockchainLifecycle.startAsync(); - }); - afterEach(async () => { - await blockchainLifecycle.revertAsync(); - }); - describe('#getBalanceAsync', () => { - it('should return the balance for an existing ERC20 token', async () => { - const aToken = tokens[0]; - const aOwnerAddress = userAddresses[0]; - const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aOwnerAddress); - const expectedBalance = new BigNumber('100000000000000000000000000'); - expect(balance).to.be.bignumber.equal(expectedBalance); - }); - it ('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { - const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; - const aOwnerAddress = userAddresses[0]; - expect(zeroEx.erc20.getBalanceAsync(nonExistentTokenAddress, aOwnerAddress)) - .to.be.rejectedWith(ZeroExError.CONTRACT_DOES_NOT_EXIST); - }); - it ('should return a balance of 0 for a non-existent owner address', async () => { - const aToken = tokens[0]; - const aNonExistentOwner = '0x198C6Ad858F213Fb31b6FE809E25040E6B964593'; - const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aNonExistentOwner); - const expectedBalance = new BigNumber('0'); - expect(balance).to.be.bignumber.equal(expectedBalance); - }); - }); -}); diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts new file mode 100644 index 000000000..22fb6e052 --- /dev/null +++ b/test/token_wrapper_test.ts @@ -0,0 +1,55 @@ +import 'mocha'; +import * as chai from 'chai'; +import chaiAsPromised = require('chai-as-promised'); +import * as Web3 from 'web3'; +import * as BigNumber from 'bignumber.js'; +import promisify = require('es6-promisify'); +import {web3Factory} from './utils/web3_factory'; +import {ZeroEx} from '../src/0x.js'; +import {ZeroExError, Token} from '../src/types'; +import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; + +const expect = chai.expect; +chai.use(chaiAsPromised); +const blockchainLifecycle = new BlockchainLifecycle(); + +describe('TokenWrapper', () => { + let web3: Web3; + let zeroEx: ZeroEx; + let userAddresses: string[]; + let tokens: Token[]; + before(async () => { + web3 = web3Factory.create(); + zeroEx = new ZeroEx(web3); + userAddresses = await promisify(web3.eth.getAccounts)(); + tokens = await zeroEx.tokenRegistry.getTokensAsync(); + }); + beforeEach(async () => { + await blockchainLifecycle.startAsync(); + }); + afterEach(async () => { + await blockchainLifecycle.revertAsync(); + }); + describe('#getBalanceAsync', () => { + it('should return the balance for an existing ERC20 token', async () => { + const aToken = tokens[0]; + const aOwnerAddress = userAddresses[0]; + const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aOwnerAddress); + const expectedBalance = new BigNumber('100000000000000000000000000'); + expect(balance).to.be.bignumber.equal(expectedBalance); + }); + it ('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { + const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; + const aOwnerAddress = userAddresses[0]; + expect(zeroEx.erc20.getBalanceAsync(nonExistentTokenAddress, aOwnerAddress)) + .to.be.rejectedWith(ZeroExError.CONTRACT_DOES_NOT_EXIST); + }); + it ('should return a balance of 0 for a non-existent owner address', async () => { + const aToken = tokens[0]; + const aNonExistentOwner = '0x198C6Ad858F213Fb31b6FE809E25040E6B964593'; + const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aNonExistentOwner); + const expectedBalance = new BigNumber('0'); + expect(balance).to.be.bignumber.equal(expectedBalance); + }); + }); +}); -- cgit From 2f16c5483569b819b292554efc736b415b43ca19 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 14:49:29 +0200 Subject: rename ERC20Contract to TokenContract --- src/contract_wrappers/token_wrapper.ts | 8 ++++---- src/types.ts | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/contract_wrappers/token_wrapper.ts b/src/contract_wrappers/token_wrapper.ts index bd815554a..fe1d0c89f 100644 --- a/src/contract_wrappers/token_wrapper.ts +++ b/src/contract_wrappers/token_wrapper.ts @@ -4,10 +4,10 @@ import {Web3Wrapper} from '../web3_wrapper'; import {assert} from '../utils/assert'; import {ContractWrapper} from './contract_wrapper'; import * as TokenArtifacts from '../artifacts/Token.json'; -import {ERC20Contract} from '../types'; +import {TokenContract} from '../types'; export class TokenWrapper extends ContractWrapper { - private tokenContractsByAddress: {[address: string]: ERC20Contract}; + private tokenContractsByAddress: {[address: string]: TokenContract}; constructor(web3Wrapper: Web3Wrapper) { super(web3Wrapper); this.tokenContractsByAddress = {}; @@ -29,13 +29,13 @@ export class TokenWrapper extends ContractWrapper { balance = _.isUndefined(balance) ? new BigNumber(0) : new BigNumber(balance); return balance; } - private async getTokenContractAsync(tokenAddress: string): Promise { + private async getTokenContractAsync(tokenAddress: string): Promise { let tokenContract = this.tokenContractsByAddress[tokenAddress]; if (!_.isUndefined(tokenContract)) { return tokenContract; } const contractInstance = await this.instantiateContractIfExistsAsync((TokenArtifacts as any), tokenAddress); - tokenContract = contractInstance as ERC20Contract; + tokenContract = contractInstance as TokenContract; this.tokenContractsByAddress[tokenAddress] = tokenContract; return tokenContract; } diff --git a/src/types.ts b/src/types.ts index 9c82c1fa6..e1c68e8ae 100644 --- a/src/types.ts +++ b/src/types.ts @@ -30,7 +30,7 @@ export interface ExchangeContract { isValidSignature: any; } -export interface ERC20Contract { +export interface TokenContract { balanceOf: { call: (address: string) => Promise; }; -- cgit From 86cdb6cb83078f9f29f473e0ebb8425a2d90f5ec Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 14:53:25 +0200 Subject: use token instead of erc20 --- src/0x.js.ts | 6 +++--- test/token_wrapper_test.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/0x.js.ts b/src/0x.js.ts index 96b290439..d231c579e 100644 --- a/src/0x.js.ts +++ b/src/0x.js.ts @@ -21,7 +21,7 @@ const MAX_DIGITS_IN_UNSIGNED_256_INT = 78; export class ZeroEx { public exchange: ExchangeWrapper; public tokenRegistry: TokenRegistryWrapper; - public erc20: TokenWrapper; + public token: TokenWrapper; private web3Wrapper: Web3Wrapper; /** * Computes the orderHash given the order parameters and returns it as a hex encoded string. @@ -137,7 +137,7 @@ export class ZeroEx { this.web3Wrapper = new Web3Wrapper(web3); this.exchange = new ExchangeWrapper(this.web3Wrapper); this.tokenRegistry = new TokenRegistryWrapper(this.web3Wrapper); - this.erc20 = new TokenWrapper(this.web3Wrapper); + this.token = new TokenWrapper(this.web3Wrapper); } /** * Sets a new provider for the web3 instance used by 0x.js @@ -146,7 +146,7 @@ export class ZeroEx { this.web3Wrapper.setProvider(provider); this.exchange.invalidateContractInstance(); this.tokenRegistry.invalidateContractInstance(); - this.erc20.invalidateContractInstances(); + this.token.invalidateContractInstances(); } /** * Signs an orderHash and returns it's elliptic curve signature diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index 22fb6e052..a15fab505 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -34,20 +34,20 @@ describe('TokenWrapper', () => { it('should return the balance for an existing ERC20 token', async () => { const aToken = tokens[0]; const aOwnerAddress = userAddresses[0]; - const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aOwnerAddress); + const balance = await zeroEx.token.getBalanceAsync(aToken.address, aOwnerAddress); const expectedBalance = new BigNumber('100000000000000000000000000'); expect(balance).to.be.bignumber.equal(expectedBalance); }); it ('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; const aOwnerAddress = userAddresses[0]; - expect(zeroEx.erc20.getBalanceAsync(nonExistentTokenAddress, aOwnerAddress)) + expect(zeroEx.token.getBalanceAsync(nonExistentTokenAddress, aOwnerAddress)) .to.be.rejectedWith(ZeroExError.CONTRACT_DOES_NOT_EXIST); }); it ('should return a balance of 0 for a non-existent owner address', async () => { const aToken = tokens[0]; const aNonExistentOwner = '0x198C6Ad858F213Fb31b6FE809E25040E6B964593'; - const balance = await zeroEx.erc20.getBalanceAsync(aToken.address, aNonExistentOwner); + const balance = await zeroEx.token.getBalanceAsync(aToken.address, aNonExistentOwner); const expectedBalance = new BigNumber('0'); expect(balance).to.be.bignumber.equal(expectedBalance); }); -- cgit From b5e496ea0f04206b74b37d71d6ba3e6975206efc Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 15:27:51 +0200 Subject: Implement zeroEx.token.getProxyAllowanceAsync --- src/contract_wrappers/token_wrapper.ts | 27 ++++++++++++++++++++++++++- src/types.ts | 8 ++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/contract_wrappers/token_wrapper.ts b/src/contract_wrappers/token_wrapper.ts index fe1d0c89f..0282d8266 100644 --- a/src/contract_wrappers/token_wrapper.ts +++ b/src/contract_wrappers/token_wrapper.ts @@ -4,7 +4,8 @@ import {Web3Wrapper} from '../web3_wrapper'; import {assert} from '../utils/assert'; import {ContractWrapper} from './contract_wrapper'; import * as TokenArtifacts from '../artifacts/Token.json'; -import {TokenContract} from '../types'; +import * as ProxyArtifacts from '../artifacts/Proxy.json'; +import {TokenContract, InternalError} from '../types'; export class TokenWrapper extends ContractWrapper { private tokenContractsByAddress: {[address: string]: TokenContract}; @@ -29,6 +30,19 @@ export class TokenWrapper extends ContractWrapper { balance = _.isUndefined(balance) ? new BigNumber(0) : new BigNumber(balance); return balance; } + /** + * Retrieves the allowance of an ERC20 token set to the 0x proxy contract by an owner address + */ + public async getProxyAllowanceAsync(tokenAddress: string, ownerAddress: string) { + assert.isETHAddressHex('ownerAddress', ownerAddress); + assert.isETHAddressHex('tokenAddress', tokenAddress); + + const tokenContract = await this.getTokenContractAsync(tokenAddress); + const proxyAddress = await this.getProxyAddressAsync(); + let allowance = await tokenContract.allowance.call(ownerAddress, proxyAddress); + allowance = _.isUndefined(allowance) ? new BigNumber(0) : new BigNumber(allowance); + return allowance; + } private async getTokenContractAsync(tokenAddress: string): Promise { let tokenContract = this.tokenContractsByAddress[tokenAddress]; if (!_.isUndefined(tokenContract)) { @@ -39,4 +53,15 @@ export class TokenWrapper extends ContractWrapper { this.tokenContractsByAddress[tokenAddress] = tokenContract; return tokenContract; } + private async getProxyAddressAsync() { + const networkIdIfExists = await this.web3Wrapper.getNetworkIdIfExistsAsync(); + const proxyNetworkConfigsIfExists = _.isUndefined(networkIdIfExists) ? + undefined : + (ProxyArtifacts as any).networks[networkIdIfExists]; + if (_.isUndefined(proxyNetworkConfigsIfExists)) { + throw new Error(InternalError.PROXY_ADDRESS_NOT_FOUND); + } + const proxyAddress = proxyNetworkConfigsIfExists.address; + return proxyAddress; + } } diff --git a/src/types.ts b/src/types.ts index e1c68e8ae..c2a048e8a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -17,6 +17,11 @@ export const ZeroExError = strEnum([ ]); export type ZeroExError = keyof typeof ZeroExError; +export const InternalError = strEnum([ + 'PROXY_ADDRESS_NOT_FOUND', +]); +export type InternalError = keyof typeof InternalError; + /** * Elliptic Curve signature */ @@ -34,6 +39,9 @@ export interface TokenContract { balanceOf: { call: (address: string) => Promise; }; + allowance: { + call: (ownerAddress: string, allowedAddress: string) => Promise; + }; } export interface TokenRegistryContract { -- cgit From 53e83a7d8168d1feace1959803d3ad5e21dff7b8 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 15:28:21 +0200 Subject: Add first test for getProxyAllowanceAsync --- test/token_wrapper_test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index a15fab505..9ce078c15 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -52,4 +52,13 @@ describe('TokenWrapper', () => { expect(balance).to.be.bignumber.equal(expectedBalance); }); }); + describe('#getProxyAllowanceAsync', () => { + it('should return 0 if no allowance set yet', async () => { + const aToken = tokens[0]; + const aOwner = userAddresses[0]; + const allowance = await zeroEx.token.getProxyAllowanceAsync(aToken.address, aOwner); + const expectedAllowance = new BigNumber('0'); + expect(allowance).to.be.bignumber.equal(expectedAllowance); + }); + }); }); -- cgit From f066b521438f6e2d4a8c32194a569e59c7079c4f Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 15:28:45 +0200 Subject: remove spaces after it keyword --- test/token_wrapper_test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index 9ce078c15..c9cd08028 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -38,13 +38,13 @@ describe('TokenWrapper', () => { const expectedBalance = new BigNumber('100000000000000000000000000'); expect(balance).to.be.bignumber.equal(expectedBalance); }); - it ('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { + it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; const aOwnerAddress = userAddresses[0]; expect(zeroEx.token.getBalanceAsync(nonExistentTokenAddress, aOwnerAddress)) .to.be.rejectedWith(ZeroExError.CONTRACT_DOES_NOT_EXIST); }); - it ('should return a balance of 0 for a non-existent owner address', async () => { + it('should return a balance of 0 for a non-existent owner address', async () => { const aToken = tokens[0]; const aNonExistentOwner = '0x198C6Ad858F213Fb31b6FE809E25040E6B964593'; const balance = await zeroEx.token.getBalanceAsync(aToken.address, aNonExistentOwner); -- cgit From 141d23f78afc822023f59a4b4dce175a8ba7cffd Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 16:30:29 +0200 Subject: Implement setProxyAllowanceAsync --- src/contract_wrappers/token_wrapper.ts | 36 ++++++++++++++++++++++++++++++---- src/types.ts | 1 + src/utils/constants.ts | 1 + 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/contract_wrappers/token_wrapper.ts b/src/contract_wrappers/token_wrapper.ts index 0282d8266..59dfc0667 100644 --- a/src/contract_wrappers/token_wrapper.ts +++ b/src/contract_wrappers/token_wrapper.ts @@ -2,11 +2,14 @@ import * as _ from 'lodash'; import * as BigNumber from 'bignumber.js'; import {Web3Wrapper} from '../web3_wrapper'; import {assert} from '../utils/assert'; +import {constants} from '../utils/constants'; import {ContractWrapper} from './contract_wrapper'; import * as TokenArtifacts from '../artifacts/Token.json'; import * as ProxyArtifacts from '../artifacts/Proxy.json'; import {TokenContract, InternalError} from '../types'; +const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 45730; + export class TokenWrapper extends ContractWrapper { private tokenContractsByAddress: {[address: string]: TokenContract}; constructor(web3Wrapper: Web3Wrapper) { @@ -31,7 +34,8 @@ export class TokenWrapper extends ContractWrapper { return balance; } /** - * Retrieves the allowance of an ERC20 token set to the 0x proxy contract by an owner address + * Retrieves the allowance in baseUnits of the ERC20 token set to the 0x proxy contract + * by an owner address */ public async getProxyAllowanceAsync(tokenAddress: string, ownerAddress: string) { assert.isETHAddressHex('ownerAddress', ownerAddress); @@ -39,9 +43,33 @@ export class TokenWrapper extends ContractWrapper { const tokenContract = await this.getTokenContractAsync(tokenAddress); const proxyAddress = await this.getProxyAddressAsync(); - let allowance = await tokenContract.allowance.call(ownerAddress, proxyAddress); - allowance = _.isUndefined(allowance) ? new BigNumber(0) : new BigNumber(allowance); - return allowance; + let allowanceInBaseUnits = await tokenContract.allowance.call(ownerAddress, proxyAddress); + allowanceInBaseUnits = _.isUndefined(allowanceInBaseUnits) ? + new BigNumber(0) : + new BigNumber(allowanceInBaseUnits); + return allowanceInBaseUnits; + } + /** + * Sets the 0x proxy contract's allowance to a specified number of a tokens' baseUnits on behalf + * of an owner address. + */ + public async setProxyAllowanceAsync(tokenAddress: string, ownerAddress: string, + amountInBaseUnits: BigNumber.BigNumber) { + assert.isETHAddressHex('ownerAddress', ownerAddress); + assert.isETHAddressHex('tokenAddress', tokenAddress); + assert.isBigNumber('amountInBaseUnits', amountInBaseUnits); + + const tokenContract = await this.getTokenContractAsync(tokenAddress); + const proxyAddress = await this.getProxyAddressAsync(); + // Hack: for some reason default estimated gas amount causes `base fee exceeds gas limit` exception + // on testrpc. Probably related to https://github.com/ethereumjs/testrpc/issues/294 + // TODO: Debug issue in testrpc and submit a PR, then remove this hack + const networkIdIfExists = await this.web3Wrapper.getNetworkIdIfExistsAsync(); + const gas = networkIdIfExists === constants.TESTRPC_NETWORK_ID ? ALLOWANCE_TO_ZERO_GAS_AMOUNT : undefined; + await tokenContract.approve(proxyAddress, amountInBaseUnits, { + from: ownerAddress, + gas, + }); } private async getTokenContractAsync(tokenAddress: string): Promise { let tokenContract = this.tokenContractsByAddress[tokenAddress]; diff --git a/src/types.ts b/src/types.ts index c2a048e8a..bf0a1d8b4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -42,6 +42,7 @@ export interface TokenContract { allowance: { call: (ownerAddress: string, allowedAddress: string) => Promise; }; + approve: (proxyAddress: string, amountInBaseUnits: BigNumber.BigNumber, opts: any) => void; } export interface TokenRegistryContract { diff --git a/src/utils/constants.ts b/src/utils/constants.ts index ec2fe744a..5a5ba0e0a 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -1,3 +1,4 @@ export const constants = { NULL_ADDRESS: '0x0000000000000000000000000000000000000000', + TESTRPC_NETWORK_ID: 50, }; -- cgit From 8df2926a1acf698f469deaf03a0de35e2179ddf2 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 16:31:02 +0200 Subject: Add test for setProxyAllowanceAsync and additional test for getProxyAllowanceAsync --- test/token_wrapper_test.ts | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index c9cd08028..3a1a3c3a5 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -53,12 +53,42 @@ describe('TokenWrapper', () => { }); }); describe('#getProxyAllowanceAsync', () => { + it('should get the proxy allowance', async () => { + const aToken = tokens[0]; + const aOwnerAddress = userAddresses[0]; + + const amountInUnits = new BigNumber('50'); + const amountInBaseUnits = ZeroEx.toBaseUnitAmount(amountInUnits, aToken.decimals); + await zeroEx.token.setProxyAllowanceAsync(aToken.address, aOwnerAddress, amountInBaseUnits); + + const allowance = await zeroEx.token.getProxyAllowanceAsync(aToken.address, aOwnerAddress); + const expectedAllowance = amountInBaseUnits; + expect(allowance).to.be.bignumber.equal(expectedAllowance); + }); it('should return 0 if no allowance set yet', async () => { const aToken = tokens[0]; - const aOwner = userAddresses[0]; - const allowance = await zeroEx.token.getProxyAllowanceAsync(aToken.address, aOwner); + const aOwnerAddress = userAddresses[0]; + const allowance = await zeroEx.token.getProxyAllowanceAsync(aToken.address, aOwnerAddress); const expectedAllowance = new BigNumber('0'); expect(allowance).to.be.bignumber.equal(expectedAllowance); }); }); + describe('#setProxyAllowanceAsync', () => { + it('should set the proxy allowance', async () => { + const aToken = tokens[0]; + const aOwnerAddress = userAddresses[0]; + + const allowanceBeforeSet = await zeroEx.token.getProxyAllowanceAsync(aToken.address, aOwnerAddress); + const expectedAllowanceBeforeAllowanceSet = new BigNumber('0'); + expect(allowanceBeforeSet).to.be.bignumber.equal(expectedAllowanceBeforeAllowanceSet); + + const amountInUnits = new BigNumber('50'); + const amountInBaseUnits = ZeroEx.toBaseUnitAmount(amountInUnits, aToken.decimals); + await zeroEx.token.setProxyAllowanceAsync(aToken.address, aOwnerAddress, amountInBaseUnits); + + const allowanceAfterSet = await zeroEx.token.getProxyAllowanceAsync(aToken.address, aOwnerAddress); + const expectedAllowanceAfterAllowanceSet = amountInBaseUnits; + expect(allowanceAfterSet).to.be.bignumber.equal(expectedAllowanceAfterAllowanceSet); + }); + }); }); -- cgit From 5e6818d3eff89347e704edde4bfee72066caedb1 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 30 May 2017 16:36:38 +0200 Subject: remove unused imports --- test/exchange_wrapper.ts | 2 -- test/token_wrapper_test.ts | 2 -- 2 files changed, 4 deletions(-) diff --git a/test/exchange_wrapper.ts b/test/exchange_wrapper.ts index 55b84ce36..e42454089 100644 --- a/test/exchange_wrapper.ts +++ b/test/exchange_wrapper.ts @@ -1,12 +1,10 @@ import 'mocha'; import * as chai from 'chai'; -import chaiAsPromised = require('chai-as-promised'); import {web3Factory} from './utils/web3_factory'; import {ZeroEx} from '../src/0x.js'; import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; const expect = chai.expect; -chai.use(chaiAsPromised); const blockchainLifecycle = new BlockchainLifecycle(); describe('ExchangeWrapper', () => { diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index 3a1a3c3a5..5ce3efb14 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -1,6 +1,5 @@ import 'mocha'; import * as chai from 'chai'; -import chaiAsPromised = require('chai-as-promised'); import * as Web3 from 'web3'; import * as BigNumber from 'bignumber.js'; import promisify = require('es6-promisify'); @@ -10,7 +9,6 @@ import {ZeroExError, Token} from '../src/types'; import {BlockchainLifecycle} from './utils/blockchain_lifecycle'; const expect = chai.expect; -chai.use(chaiAsPromised); const blockchainLifecycle = new BlockchainLifecycle(); describe('TokenWrapper', () => { -- cgit From 9409e0aba1d1fa62a60c25149ae1b7115de9e2c9 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Wed, 31 May 2017 11:16:57 +0200 Subject: Add transfer function and tests for it --- src/contract_wrappers/token_wrapper.ts | 17 ++++++++++++++++- src/types.ts | 1 + test/token_wrapper_test.ts | 19 +++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/contract_wrappers/token_wrapper.ts b/src/contract_wrappers/token_wrapper.ts index 59dfc0667..e93b6b7c2 100644 --- a/src/contract_wrappers/token_wrapper.ts +++ b/src/contract_wrappers/token_wrapper.ts @@ -54,7 +54,7 @@ export class TokenWrapper extends ContractWrapper { * of an owner address. */ public async setProxyAllowanceAsync(tokenAddress: string, ownerAddress: string, - amountInBaseUnits: BigNumber.BigNumber) { + amountInBaseUnits: BigNumber.BigNumber): Promise { assert.isETHAddressHex('ownerAddress', ownerAddress); assert.isETHAddressHex('tokenAddress', tokenAddress); assert.isBigNumber('amountInBaseUnits', amountInBaseUnits); @@ -71,6 +71,21 @@ export class TokenWrapper extends ContractWrapper { gas, }); } + /** + * Transfers `amountInBaseUnits` ERC20 tokens from `fromAddress` to `toAddress`. + */ + public async transferAsync(tokenAddress: string, fromAddress: string, toAddress: string, + amountInBaseUnits: BigNumber.BigNumber): Promise { + assert.isETHAddressHex('tokenAddress', tokenAddress); + assert.isETHAddressHex('fromAddress', fromAddress); + assert.isETHAddressHex('toAddress', toAddress); + assert.isBigNumber('amountInBaseUnits', amountInBaseUnits); + + const tokenContract = await this.getTokenContractAsync(tokenAddress); + await tokenContract.transfer(toAddress, amountInBaseUnits, { + from: fromAddress, + }); + } private async getTokenContractAsync(tokenAddress: string): Promise { let tokenContract = this.tokenContractsByAddress[tokenAddress]; if (!_.isUndefined(tokenContract)) { diff --git a/src/types.ts b/src/types.ts index bf0a1d8b4..418cf9802 100644 --- a/src/types.ts +++ b/src/types.ts @@ -42,6 +42,7 @@ export interface TokenContract { allowance: { call: (ownerAddress: string, allowedAddress: string) => Promise; }; + transfer: (to: string, amountInBaseUnits: BigNumber.BigNumber, opts: any) => Promise; approve: (proxyAddress: string, amountInBaseUnits: BigNumber.BigNumber, opts: any) => void; } diff --git a/test/token_wrapper_test.ts b/test/token_wrapper_test.ts index 5ce3efb14..113dd32d6 100644 --- a/test/token_wrapper_test.ts +++ b/test/token_wrapper_test.ts @@ -28,6 +28,25 @@ describe('TokenWrapper', () => { afterEach(async () => { await blockchainLifecycle.revertAsync(); }); + describe('#transferAsync', () => { + it('should successfully transfer tokens', async () => { + const token = tokens[0]; + const fromAddress = userAddresses[0]; + const toAddress = userAddresses[1]; + const preBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); + expect(preBalance).to.be.bignumber.equal(0); + await zeroEx.token.transferAsync(token.address, fromAddress, toAddress, new BigNumber(42)); + const postBalance = await zeroEx.token.getBalanceAsync(token.address, toAddress); + expect(postBalance).to.be.bignumber.equal(42); + }); + it('should throw a CONTRACT_DOES_NOT_EXIST error for a non-existent token contract', async () => { + const nonExistentTokenAddress = '0x9dd402f14d67e001d8efbe6583e51bf9706aa065'; + const aOwnerAddress = userAddresses[0]; + expect(zeroEx.token.transferAsync( + nonExistentTokenAddress, userAddresses[0], userAddresses[1], new BigNumber(42), + )).to.be.rejectedWith(ZeroExError.CONTRACT_DOES_NOT_EXIST); + }); + }); describe('#getBalanceAsync', () => { it('should return the balance for an existing ERC20 token', async () => { const aToken = tokens[0]; -- cgit