Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logging Refactoring #976

Merged
merged 5 commits into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 2 additions & 40 deletions cli/lib/nf3.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,6 @@ class Nf3 {

BLOCK_STAKE = DEFAULT_BLOCK_STAKE;

// nonce = 0;

latestWithdrawHash;

mnemonic = {};
Expand Down Expand Up @@ -152,8 +150,6 @@ class Nf3 {
async setEthereumSigningKey(key) {
this.ethereumSigningKey = key;
this.ethereumAddress = await this.getAccounts();
// clear the nonce as we're using a fresh account
// this.nonce = 0;
}

/**
Expand Down Expand Up @@ -229,7 +225,6 @@ class Nf3 {
data: unsignedTransaction,
});
} catch (error) {
// logger.warn(`estimateGas failed. Falling back to constant value`);
gasLimit = GAS; // backup if estimateGas failed
}
return Math.ceil(Number(gasLimit) * GAS_MULTIPLIER); // 50% seems a more than reasonable buffer.
Expand All @@ -242,11 +237,9 @@ class Nf3 {
const res = (await axios.get(GAS_ESTIMATE_ENDPOINT)).data.result;
proposedGasPrice = Number(res?.ProposeGasPrice) * 10 ** 9;
} catch (error) {
// logger.warn('Gas Estimation Failed, using previous block gasPrice');
try {
proposedGasPrice = Number(await this.web3.eth.getGasPrice());
} catch (err) {
// logger.warn('Failed to get previous block gasprice. Falling back to default');
proposedGasPrice = GAS_PRICE;
}
}
Expand All @@ -269,11 +262,6 @@ class Nf3 {
const gasPrice = await this.estimateGasPrice();
// Estimate the gasLimit
const gas = await this.estimateGas(contractAddress, unsignedTransaction);
// logger.debug(
// `Transaction gasPrice was set at ${Math.ceil(
// gasPrice / 10 ** 9,
// )} GWei, gas limit was set at ${gas}`,
// );
const tx = {
from: this.ethereumAddress,
to: contractAddress,
Expand All @@ -289,7 +277,6 @@ class Nf3 {
this.web3.eth
.sendSignedTransaction(signed.rawTransaction)
.once('receipt', receipt => {
// logger.debug(`Transaction ${receipt.transactionHash} has been received.`);
resolve(receipt);
})
.on('error', err => {
Expand Down Expand Up @@ -414,7 +401,6 @@ class Nf3 {
);
resolve(receipt);
} catch (err) {
// logger.error('Deposit transaction failed');
reject(err);
}
});
Expand Down Expand Up @@ -650,11 +636,9 @@ class Nf3 {
this.intervalIDs.push(
setInterval(() => {
connection._ws.ping();
// logger.debug('sent websocket ping');
}, WEBSOCKET_PING_TIME),
);
// and a listener for the pong
// connection._ws.on('pong', () => logger.debug('websocket received pong'));
logger.debug('Liquidity provider websocket connection opened');
connection.send('instant');
};
Expand Down Expand Up @@ -896,11 +880,9 @@ class Nf3 {
this.intervalIDs.push(
setInterval(() => {
connection._ws.ping();
// logger.debug('sent websocket ping');
}, WEBSOCKET_PING_TIME),
);
// and a listener for the pong
// connection._ws.on('pong', () => logger.debug('websocket received pong'));
logger.debug('Proposer websocket connection opened');
connection.send('blocks');
};
Expand Down Expand Up @@ -964,11 +946,9 @@ class Nf3 {
this.intervalIDs.push(
setInterval(() => {
connection._ws.ping();
// logger.debug('sent challenge websocket ping');
}, WEBSOCKET_PING_TIME),
);
// and a listener for the pong
// connection._ws.on('pong', () => logger.debug('Challenge websocket received pong'));
logger.debug('Challenge websocket connection opened');
connection.send('challenge');
};
Expand Down Expand Up @@ -1127,27 +1107,9 @@ class Nf3 {
return res.data.commitments;
}

// /**
// Set a Web3 Provider URL
// */
// async setWeb3Provider() {
// this.web3 = new Web3(this.web3WsUrl);
// this.web3.eth.transactionBlockTimeout = 200;
// this.web3.eth.transactionConfirmationBlocks = 12;
// if (typeof window !== 'undefined') {
// if (window.ethereum && this.ethereumSigningKey === '') {
// this.web3 = new Web3(window.ethereum);
// await window.ethereum.request({ method: 'eth_requestAccounts' });
// } else {
// // Metamask not available
// throw new Error('No Web3 provider found');
// }
// }
// }

/**
Set a Web3 Provider URL
*/
* Set a Web3 Provider URL
*/
async setWeb3Provider() {
// initialization of web3 provider has been taken from common-files/utils/web3.mjs
// Target is to mainain web3 socker alive
Expand Down
9 changes: 5 additions & 4 deletions cli/src/liquidity-provider.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Command } from 'commander/esm.mjs';
import clear from 'clear';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import logger from '../../common-files/utils/logger.mjs';
import Nf3 from '../lib/nf3.mjs';
import { APPROVE_AMOUNT, TOKEN_TYPE } from '../lib/constants.mjs';
import { setEnvironment, getCurrentEnvironment } from '../lib/environment.mjs';
Expand All @@ -30,7 +31,7 @@ Does the preliminary setup and starts listening on the websocket
*/
async function startProvider(testEnvironment) {
clear();
console.log('Starting Liquidity Provider...');
logger.info('Starting Liquidity Provider...');
if (typeof testEnvironment !== 'undefined') {
setEnvironment(testEnvironment);
} else {
Expand All @@ -39,7 +40,7 @@ async function startProvider(testEnvironment) {
const nf3Env = getCurrentEnvironment().currentEnvironment;
const nf3 = new Nf3(advanceWithdrawalEthereumSigningKey, nf3Env);
await nf3.init(defaultMnemonic);
if (await nf3.healthcheck('optimist')) console.log('Healthcheck passed');
if (await nf3.healthcheck('optimist')) logger.info('Healthcheck passed');
else throw new Error('Healthcheck failed');
const erc20Address = await nf3.getContractAddress('ERC20Mock');

Expand All @@ -57,9 +58,9 @@ async function startProvider(testEnvironment) {
const emitter = await nf3.getInstantWithdrawalRequestedEmitter();
emitter.on('data', async (withdrawTransactionHash, paidBy, amount) => {
await nf3.advanceInstantWithdrawal(withdrawTransactionHash);
console.log(`Serviced instant-withdrawal request from ${paidBy}, with fee ${amount}`);
logger.info(`Serviced instant-withdrawal request from ${paidBy}, with fee ${amount}`);
});
console.log('Listening for incoming events');
logger.info('Listening for incoming events');
}

startProvider(environment);
26 changes: 18 additions & 8 deletions common-files/utils/contract.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export const contractPath = contractName => {
export async function getContractInterface(contractName) {
const path = contractPath(contractName);
const contractInterface = JSON.parse(fs.readFileSync(path, 'utf8'));
// logger.trace('\ncontractInterface:', contractInterface);
return contractInterface;
}

Expand All @@ -37,7 +36,12 @@ export async function getContractInstance(contractName, deployedAddress) {
// grab a 'from' account if one isn't set
if (!options.from) {
const accounts = await web3.eth.getAccounts();
logger.debug('blockchain accounts are: ', accounts);

logger.debug({
msg: 'blockchain accounts',
accounts,
});

[options.from] = accounts;
}
const contractInterface = await getContractInterface(contractName);
Expand All @@ -49,7 +53,6 @@ export async function getContractInstance(contractName, deployedAddress) {
const contractInstance = deployedAddress
? new web3.eth.Contract(contractInterface.abi, deployedAddress, options)
: new web3.eth.Contract(contractInterface.abi, options);
// logger.trace('\ncontractInstance:', contractInstance);

return contractInstance;
}
Expand All @@ -76,10 +79,11 @@ export async function deploy(contractName, constructorParams, { from, gas, passw
throw new Error(err);
})
.then(deployedContractInstance => {
// logger.trace('deployed contract instance:', deployedContractInstance);
logger.info(
`${contractName} contract deployed at address ${deployedContractInstance.options.address}`,
); // instance with the new contract address
logger.info({
msg: 'Contract deployed',
contractName,
address: deployedContractInstance.options.address,
}); // instance with the new contract address

return deployedContractInstance.options.address;
});
Expand All @@ -106,10 +110,16 @@ export async function waitForContract(contractName) {
} catch (err) {
error = err;
errorCount++;
logger.warn(`Unable to get a ${contractName} contract instance will try again in 3 seconds`);

logger.warn({
msg: 'Unable to get contract instance, retrying in 3 secs',
contractName,
});

await new Promise(resolve => setTimeout(() => resolve(), 3000)); // eslint-disable-line no-await-in-loop
}
}
if (error) throw error;

return instance;
}
2 changes: 1 addition & 1 deletion common-files/utils/crypto/poseidon/poseidon.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function poseidonHash(_inputs) {
state = sbox(state, f, p, r);
state = mix(state, m);
}
// console.log('MATRIX', m);

return generalise(state[0]);
}

Expand Down
Loading