abi.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. Decodes Data into values, for a given signature.
  3. @module ABI
  4. */
  5. const _ = global._;
  6. const { ipcMain: ipc } = require('electron');
  7. const abi = require('ethereumjs-abi');
  8. function isHexType(type) {
  9. return _.includes(['address', 'bytes'], type) || type.match(/bytes\d+/g);
  10. }
  11. function padLeft(string, chars) {
  12. return new Array(chars - string.length + 1).join('0') + string;
  13. }
  14. ipc.on('backendAction_decodeFunctionSignature', (event, _signature, _data) => {
  15. const data = _data.slice(10, _data.length);
  16. const signature = _signature.match(/\((.+)\)/i);
  17. if (!signature) return;
  18. const paramTypes = signature[1].split(',');
  19. try {
  20. const paramsResponse = abi.rawDecode(paramTypes, new Buffer(data, 'hex'));
  21. const paramsDictArr = [];
  22. // Turns addresses into proper hex string
  23. // Turns numbers into their decimal string version
  24. paramTypes.forEach((type, index) => {
  25. const conversionFlag = isHexType(type) ? 'hex' : null;
  26. const prefix = isHexType(type) ? '0x' : '';
  27. paramsResponse[index] = paramsResponse[index].toString(conversionFlag);
  28. const res = type.match(/bytes(\d+)/i);
  29. if (type === 'address') {
  30. paramsResponse[index] = padLeft(paramsResponse[index], 40);
  31. } else if (res) {
  32. paramsResponse[index] = padLeft(
  33. paramsResponse[index],
  34. Number(res[1]) * 2
  35. );
  36. }
  37. paramsDictArr.push({ type, value: prefix + paramsResponse[index] });
  38. });
  39. event.sender.send('uiAction_decodedFunctionSignatures', paramsDictArr);
  40. } catch (e) {
  41. console.warn('ABI.js Warning:', e.message);
  42. }
  43. });