ethers.js/src.ts/providers/web3-provider.ts

95 lines
2.7 KiB
TypeScript
Raw Normal View History

2018-06-13 22:39:39 +03:00
'use strict';
import { JsonRpcProvider } from './json-rpc-provider';
2018-06-18 12:42:41 +03:00
import { defineReadOnly } from '../utils/properties';
// Imported Types
import { Networkish } from '../utils/networks';
2018-07-16 07:48:41 +03:00
import * as errors from '../errors';
2018-06-13 22:39:39 +03:00
// Exported Types
export type AsyncSendable = {
isMetaMask?: boolean;
host?: string;
path?: string;
2018-07-31 06:14:07 +03:00
sendAsync?: (request: any, callback: (error: any, response: any) => void) => void
send?: (request: any, callback: (error: any, response: any) => void) => void
}
2018-06-13 22:39:39 +03:00
/*
@TODO
utils.defineProperty(Web3Signer, 'onchange', {
});
2018-07-16 07:09:13 +03:00
*/
2018-06-13 22:39:39 +03:00
export class Web3Provider extends JsonRpcProvider {
readonly _web3Provider: AsyncSendable;
2018-07-31 06:14:07 +03:00
private _sendAsync: (request: any, callback: (error: any, response: any) => void) => void;
2018-06-13 22:39:39 +03:00
constructor(web3Provider: AsyncSendable, network?: Networkish) {
2018-07-31 06:14:07 +03:00
// HTTP has a host; IPC has a path.
super(web3Provider.host || web3Provider.path || '', network);
errors.checkNew(this, Web3Provider);
if (web3Provider) {
if (web3Provider.sendAsync) {
this._sendAsync = web3Provider.sendAsync.bind(web3Provider);
} else if (web3Provider.send) {
this._sendAsync = web3Provider.send.bind(web3Provider);
}
}
2018-06-13 22:39:39 +03:00
2018-07-31 06:14:07 +03:00
if (!web3Provider || !this._sendAsync) {
2018-06-13 22:39:39 +03:00
errors.throwError(
'invalid web3Provider',
errors.INVALID_ARGUMENT,
{ arg: 'web3Provider', value: web3Provider }
);
}
2018-06-18 12:42:41 +03:00
defineReadOnly(this, '_web3Provider', web3Provider);
2018-06-13 22:39:39 +03:00
}
2018-06-15 11:18:17 +03:00
send(method: string, params: any): Promise<any> {
2018-06-13 22:39:39 +03:00
// Metamask complains about eth_sign (and on some versions hangs)
if (method == 'eth_sign' && this._web3Provider.isMetaMask) {
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
method = 'personal_sign';
params = [ params[1], params[0] ];
}
return new Promise((resolve, reject) => {
var request = {
method: method,
params: params,
id: 42,
jsonrpc: "2.0"
};
2018-07-31 06:14:07 +03:00
this._sendAsync(request, function(error, result) {
2018-06-13 22:39:39 +03:00
if (error) {
reject(error);
return;
}
if (result.error) {
// @TODO: not any
var error: any = new Error(result.error.message);
error.code = result.error.code;
error.data = result.error.data;
reject(error);
return;
}
resolve(result.result);
});
});
}
}