Skip to content

Commit

Permalink
Fix metamask module
Browse files Browse the repository at this point in the history
  • Loading branch information
olekon committed Feb 14, 2021
1 parent 1a9db83 commit 58e67e4
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 114 deletions.
40 changes: 16 additions & 24 deletions src/components/common/sign.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
import * as message from './errorMessage.js';
import metamask from '../../scripts/metamask.js'
import metamask from '../../scripts/metamask.js';

/**
* Signs transaction with metamask and sends it to the node.
* Shows notification depending on the outcome
* @param {Ethereum transaction object} tx
* Signs transaction with metamask and sends it to the node.
* Shows notification depending on the outcome
* @param {Ethereum transaction object} tx
*/
const sign = tx => {
metamask.sendTx(tx)
.then(txHash => {
message.showTransactionSent(tx.chainId, txHash);
console.log(JSON.stringify(txHash));
})
.catch(error=> {
message.showError(error);
})
const sign = (tx) => {
metamask
.sendTx(tx)
.then((txHash) => {
message.showTransactionSent(tx.chainId, txHash);
console.log(JSON.stringify(txHash));
})
.catch((error) => {
message.showError(error);
});
};

/* metamask.sendTx(tx, function(result) {
if(result.error) {
message.showError(result.errorCode);
} else {
message.showTransactionSent(tx.chainId, result.result[0]);
console.log(JSON.stringify(result));
}
}); */
}

export {sign}
export { sign };
174 changes: 84 additions & 90 deletions src/scripts/metamask.js
Original file line number Diff line number Diff line change
@@ -1,124 +1,118 @@

import errorCodes from './errorCodes.js';

function Metamask() {
var isLoaded = false;
var deniedTransactionSignature = "User denied transaction signature";
var deniedTransactionSignature = 'User denied transaction signature';

//проверяет есть ли коннект к метамаску (инжекнута ли им web3)
var _checkWeb3 = function () {
return window.web3 && window.web3.eth;
}
//проверяет есть ли метамаск
var _checkMetamaskPresence = function () {
return !!window.ethereum;
};

//обрабатывает ошибки после отправки транзакции в метамаск
var _processError = function (error) {
if (error.message && error.message.includes(deniedTransactionSignature)) {
if (
error.message &&
error.message.includes(deniedTransactionSignature)
) {
return errorCodes.metamaskReject;
} if (error.message && error.message.includes(deniedMessageSignature)) {
}
if (error.message && error.message.includes(deniedMessageSignature)) {
return errorCodes.metamaskMessageSignReject;
} else {
return errorCodes.unknownError;
}
}
};

//устанавливает точное значение газ лимита для метамаска
var _setGasLimit = function (transaction) {
//чтобы метамаск корректно понял переданное значение gasLimit и не пересчитвал его сам - нужно установить параметр gas в транзакции в нужное число
transaction.gas = transaction.gasLimit;
return transaction;
}


};

this.decrypt = function() {
this.decrypt = function () {
return new Promise(function (resolve, reject) {
if (window.ethereum && !isLoaded) {
window.web3 = new Web3(ethereum);
isLoaded = true;
}
if (window.ethereum) {
ethereum.enable()
.then(() => {
_decrypt()
.then(account => {
resolve(account);
})
.catch(error => {
reject(error);
window.ethereum
.request({ method: 'eth_requestAccounts' })
.then(() => {
_decrypt()
.then((account) => {
resolve(account);
})
.catch((error) => {
reject(error);
});
})
})
.catch(() => {
//если пользователь отменил, то скидываем прогрузку, чтобы запросить повторно
isLoaded = false;
reject(errorCodes.metamaskRejectAccess);
})
.catch(() => {
//если пользователь отменил, то скидываем прогрузку, чтобы запросить повторно
isLoaded = false;
reject(errorCodes.metamaskRejectAccess);
});
} else {
_decrypt()
.then(account => {
resolve(account);
})
.catch(error => {
reject(error);
})
}
})
}

var _decrypt = function () {
return new Promise(function (resolve, reject) {
if (!_checkWeb3()) {
reject(errorCodes.metamaskConnectFailed);
} else {
window.web3.eth.getAccounts(function (err, accounts) {
if (err || !accounts.length) {
reject(errorCodes.metamaskLocked);
} else {
resolve(accounts[0]);
}
//SSL
})
}
})
}
});
};

var _decrypt = function () {
if (!_checkMetamaskPresence()) {
return Promise.reject(errorCodes.metamaskConnectFailed);
} else {
return window.ethereum
.request({ method: 'eth_accounts' })
.then((accounts) => {
return accounts.length
? accounts[0]
: Promise.reject(errorCodes.metamaskLocked);
});
}
};

//Отправляет в метамаск транзакцию
this.sendTx = function (transaction, callback) {
this.sendTx = function (transaction) {
let thisObject = this;
return new Promise(function (resolve, reject) {
//достаем аккаунт
thisObject.decrypt()
.then(account=>{
if(transaction.from.toLowerCase() != account.toLowerCase()) {
reject(errorCodes.metamaskWrongAccount);
} else {
window.web3.version.getNetwork(function (err, network) {
if(err) {
reject(errorCodes.metamaskException);
} else {
if(transaction.chainId != network) {
reject(errorCodes.metamaskWrongNetwork);
} else {
window.web3.eth.sendTransaction(_setGasLimit(transaction), function (err, txHash) {
if (err) {
reject(_processError(err));
}
else {
resolve(txHash);
}
})
}
}
})
}
})
.catch(error=>{
reject(error);
})
})
}

thisObject
.decrypt()
.then((account) => {
if (
transaction.from.toLowerCase() != account.toLowerCase()
) {
reject(errorCodes.metamaskWrongAccount);
} else {
ethereum
.request({ method: 'net_version' })
.then((network) => {
if (transaction.chainId != network) {
reject(errorCodes.metamaskWrongNetwork);
} else {
window.ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
..._setGasLimit(
transaction
),
},
],
})
.then((result) => {
resolve(result);
}).catch(err => {
reject(_processError(err));
});
}
});
}
})
.catch((error) => {
reject(error);
});
});
};
}

export default new Metamask();

0 comments on commit 58e67e4

Please sign in to comment.