Skip to content

Commit

Permalink
Merge pull request #29 from ParadigmFoundation/refactor/instantiate-w…
Browse files Browse the repository at this point in the history
…ith-provider

Refactor/instantiate with provider
  • Loading branch information
Henry Harder authored Jan 14, 2020
2 parents d5484cf + 0ea168c commit 04d6e63
Show file tree
Hide file tree
Showing 5 changed files with 275 additions and 261 deletions.
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"private": false,
"scripts": {
"build": "tsc",
"test": "yarn start:snapshot && sleep 2 && yarn test:ci && yarn stop:snapshot",
"test": "yarn start:snapshot && sleep 2 && yarn test:ci; yarn stop:snapshot",
"test:ci": "ts-mocha --exit test/*_test.ts",
"clean": "rm -rf node_modules dist",
"compile:assets": "yarn build && webpack",
Expand Down Expand Up @@ -36,7 +36,7 @@
"@habsyr/erc20-token": "^0.2.0",
"axios": "^0.19.0",
"dotenv": "^6.2.0",
"web3": "1.2.0"
"web3-utils": "1.2.4"
},
"devDependencies": {
"@0x/types": "^2.4.3",
Expand All @@ -61,7 +61,8 @@
"webpack": "^4.32.2",
"webpack-cli": "^3.3.2",
"webpack-dev-middleware": "^3.6.0",
"webpack-dev-server": "^3.4.1"
"webpack-dev-server": "^3.4.1",
"web3": "1.2.4"
},
"files": [
"dist/*.js",
Expand Down
68 changes: 12 additions & 56 deletions src/DealerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ERC20Token } from "@habsyr/erc20-token";
import assert from "assert";
import axios from "axios";
import { Provider, SupportedProvider, TransactionReceiptWithDecodedLogs } from "ethereum-types";
import Web3 from "web3";
import { fromWei, toWei } from "web3-utils";

import {
convertZeroExTransactionToDealerFill,
Expand All @@ -32,9 +32,6 @@ export class DealerClient {
/** Dealer server RPC server URL. */
private readonly dealerUrl: URL;

/** Stores the Ethereum JSONRPC provider URL for server-side usage. */
private readonly web3Url: URL;

/** Base API path for the dealer server. */
private readonly apiBase: string;

Expand All @@ -51,10 +48,7 @@ export class DealerClient {
*/
public tokens: { [ticker: string]: string };

/** Main Web3 instance for interacting with Ethereum. */
public web3: Web3;

/** Provides additional convenience methods for interacting with web3. */
/** Provides convenience methods for interacting with Ethereum. */
public web3Wrapper: Web3Wrapper;

/** Provider instance used to interact with Ethereum. */
Expand All @@ -72,9 +66,6 @@ export class DealerClient {
/** Set to 'true' after a successful .init(), must be called before use. */
public initialized: boolean;

/** Set to 'true' if browser environment is detected. */
public isBrowser: boolean;

/** Default gas price to use for allowance transactions (in wei). */
public GAS_PRICE: BigNumber;

Expand All @@ -94,16 +85,15 @@ export class DealerClient {
* setting of attempting to load a web3 provider through the browser.
*
* @param dealerUri the base RPC API path for the dealer server
* @param web3Uri optional Ethereum JSONRPC url for server-side usage
* @param txPriority optionally set the gas price (via etherchain) as "fast", "average", or "safeLow"
* @param provider an ethereum provider
* @param options optional configuration to allow non standard usages of the class
*/
constructor(dealerUri: string, options: DealerOptions = {}) {
const { takerAddress, providerUrl, txPriority = "fast" } = options;
constructor(dealerUri: string, provider: Provider, options: DealerOptions = {}) {
const { takerAddress, txPriority = "fast" } = options;
this.initialized = false;

this.web3 = null;
this.web3Wrapper = null;
this.provider = null;
this.provider = provider;
this.web3Wrapper = new Web3Wrapper(this.provider);

this.networkId = null;
this.coinbase = takerAddress || null;
Expand All @@ -113,10 +103,6 @@ export class DealerClient {

this.dealerUrl = new URL(dealerUri);
this.apiBase = `${this.dealerUrl.href}api/v${DealerClient.COMPATIBLE_VERSION}`;

if (providerUrl) {
this.web3Url = new URL(providerUrl);
}
}

/**
Expand All @@ -128,27 +114,16 @@ export class DealerClient {
* @returns A promise that resolves when initialization is complete.
*/
public async init(): Promise<void> {
if (this.web3Url) {
this.isBrowser = false;
this.web3 = new Web3(this.web3Url.href);
this.provider = this.web3.currentProvider;
} else {
await this._connectMetamask();
this.isBrowser = true;
this.provider = new MetamaskSubprovider((window as any).ethereum);
}

this.web3Wrapper = new Web3Wrapper(this.web3.currentProvider);
this.networkId = await this.web3Wrapper.getNetworkIdAsync();
this.contractWrappers = new ContractWrappers(
this.web3.currentProvider,
this.provider,
{
networkId: this.networkId,
},
);

// set coinbase if not already set as configuration option
this.coinbase = this.coinbase || await this.web3.eth.getCoinbase();
this.coinbase = this.coinbase || await this.web3Wrapper.getAvailableAddressesAsync().then(addresses => addresses[0]);

this.erc20Token = new ERC20Token(this.contractWrappers.getProvider());
this.GAS_PRICE = await getGasPrice(this.txPriority);
Expand Down Expand Up @@ -444,7 +419,7 @@ export class DealerClient {
*/
public fromWei(weiAmount: string): string {
assert(typeof weiAmount === "string", "pass amounts as strings to avoid precision errors");
return this.web3.utils.fromWei(weiAmount);
return fromWei(weiAmount);
}

/**
Expand All @@ -465,7 +440,7 @@ export class DealerClient {
*/
public toWei(etherAmount: string): string {
assert(typeof etherAmount === "string", "pass amounts as strings to avoid precision errors");
return this.web3.utils.toWei(etherAmount);
return toWei(etherAmount);
}

/**
Expand Down Expand Up @@ -503,25 +478,6 @@ export class DealerClient {
return Object.keys(this.tokens);
}

private async _connectMetamask(): Promise<void> {
assert(window, "not in browser environment");
const { web3, ethereum } = (window as any);
assert(web3 || ethereum, "unsupported browser (must be a web3 browser)");

if (ethereum) {
try {
await ethereum.enable();
this.web3 = new Web3(ethereum);
} catch (error) {
throw new Error("user denied site access");
}
Object.defineProperty(global, "web3", this.web3);
} else {
this.web3 = new Web3(web3.currentProvider);
Object.defineProperty(window, "web3", this.web3);
}
}

private async _callAny(url: string, method: "GET" | "POST", data?: any): Promise<any> {
const response = await axios(
url,
Expand Down
3 changes: 0 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ export interface DealerOptions {
/** Address to use to sign and fill orders. */
takerAddress?: string;

/** Ethereum JSONRPC provider url (server-side only) */
providerUrl?: string;

/** Optional gas price selector (fast, safeLow, etc.) */
txPriority?: GasPriority;
}
Expand Down
3 changes: 1 addition & 2 deletions test/spec_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { ContractWrappers } from "@0x/contract-wrappers";
import { BigNumber } from "@0x/utils";
import assert from "assert";
import { Server } from "http";
import Redis from "ioredis";
import Web3 from "web3";

import { DealerClient } from "../src/DealerClient";
Expand Down Expand Up @@ -82,7 +81,7 @@ describe("Zaidan client unit tests", function (): void {
clientAddress = accounts[parseInt(CLIENT_ACCOUNT_INDEX)];
dealerAddress = accounts[parseInt(DEALER_ACCOUNT_INDEX)];

client = new DealerClient(DEALER_URL, { providerUrl: WEB3_URL, takerAddress: clientAddress });
client = new DealerClient(DEALER_URL, web3.currentProvider, { takerAddress: clientAddress });
await client.init();
});

Expand Down
Loading

0 comments on commit 04d6e63

Please sign in to comment.