abi.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { AbiCoder } from './ethersUtils.js';
  2. import { TronWeb } from '../tronweb.js';
  3. import { ADDRESS_PREFIX, ADDRESS_PREFIX_REGEX } from './address.js';
  4. import { FunctionFragment, AbiParamsCommon, AbiInputsType } from '../types/ABI.js';
  5. const abiCoder = new AbiCoder();
  6. function _addressToHex(value: string) {
  7. return TronWeb.address.toHex(value).replace(ADDRESS_PREFIX_REGEX, '0x');
  8. }
  9. export function decodeParams(names: string[], types: string[], output: string, ignoreMethodHash = false) {
  10. if (ignoreMethodHash && output.replace(/^0x/, '').length % 64 === 8) output = '0x' + output.replace(/^0x/, '').substring(8);
  11. if (output.replace(/^0x/, '').length % 64) {
  12. throw new Error('The encoded string is not valid. Its length must be a multiple of 64.');
  13. }
  14. // workaround for unsupported trcToken type
  15. types = types.map((type) => {
  16. if (/trcToken/.test(type)) {
  17. type = type.replace(/trcToken/, 'uint256');
  18. }
  19. return type;
  20. });
  21. return abiCoder.decode(types, output).reduce(
  22. (obj, arg, index) => {
  23. if (types[index] == 'address') {
  24. arg = ADDRESS_PREFIX + arg.substr(2).toLowerCase();
  25. }
  26. if (names.length) {
  27. obj[names[index]] = arg;
  28. } else {
  29. obj.push(arg);
  30. }
  31. return obj;
  32. },
  33. names.length ? {} : []
  34. );
  35. }
  36. export function encodeParams(types: string[], values: any[]) {
  37. for (let i = 0; i < types.length; i++) {
  38. if (types[i] === 'address') {
  39. values[i] = TronWeb.address.toHex(values[i]).replace(ADDRESS_PREFIX_REGEX, '0x');
  40. }
  41. }
  42. return abiCoder.encode(types, values);
  43. }
  44. function extractSize(type: string) {
  45. const size = type.match(/([a-zA-Z0-9])(\[.*\])/);
  46. return size ? size[2] : '';
  47. }
  48. function extractArrayDim(type: string) {
  49. const size = extractSize(type);
  50. return (size.match(/\]\[/g) || []).length + 1;
  51. }
  52. export function encodeParamsV2ByABI(funABI: FunctionFragment, args: any[]) {
  53. const types: string[] = [];
  54. const buildFullTypeDefinition = (typeDef: AbiParamsCommon): string => {
  55. if (typeDef && typeDef.type.indexOf('tuple') === 0 && typeDef.components) {
  56. const innerTypes = typeDef.components.map((innerType: AbiParamsCommon) => {
  57. return buildFullTypeDefinition(innerType);
  58. });
  59. return `tuple(${innerTypes.join(',')})${extractSize(typeDef.type)}`;
  60. }
  61. if (/trcToken/.test(typeDef.type)) return typeDef.type.replace(/trcToken/, 'uint256');
  62. return typeDef.type;
  63. };
  64. const convertTypes = (types: string[]) => {
  65. for (let i = 0; i < types.length; i++) {
  66. const type = types[i];
  67. if (/trcToken/.test(type)) types[i] = type.replace(/trcToken/, 'uint256');
  68. }
  69. };
  70. const convertAddresses = (addrArr: string | string[]) => {
  71. if (Array.isArray(addrArr)) {
  72. addrArr.forEach((addrs, i) => {
  73. addrArr[i] = convertAddresses(addrs) as string;
  74. });
  75. return addrArr;
  76. } else {
  77. return _addressToHex(addrArr);
  78. }
  79. };
  80. const mapTuple = (components: ReadonlyArray<FunctionFragment>, args: any[], dimension: number) => {
  81. if (dimension > 1) {
  82. if (args.length) {
  83. args.forEach((arg) => {
  84. mapTuple(components, arg, dimension - 1);
  85. });
  86. }
  87. } else {
  88. if (args.length && dimension) {
  89. args.forEach((arg) => {
  90. encodeArgs(components, arg);
  91. });
  92. }
  93. }
  94. };
  95. const encodeArgs = (inputs: ReadonlyArray<AbiParamsCommon> = [], args: any[]) => {
  96. if (inputs.length)
  97. inputs.forEach((input: AbiParamsCommon, i: number) => {
  98. const type = input.type;
  99. if (args[i])
  100. if (type === 'address') args[i] = _addressToHex(args[i]);
  101. else if (type.match(/^([^\x5b]*)(\x5b|$)/)![0] === 'address[') convertAddresses(args[i]);
  102. else if (type.indexOf('tuple') === 0)
  103. if (extractSize(type)) {
  104. const dimension = extractArrayDim(type);
  105. mapTuple(input.components!, args[i], dimension);
  106. } else encodeArgs(input.components!, args[i]);
  107. });
  108. };
  109. if (funABI.inputs && funABI.inputs.length) {
  110. for (let i = 0; i < funABI.inputs.length; i++) {
  111. const type = funABI.inputs[i].type;
  112. // "false" will be converting to `false` and "true" will be working
  113. // fine as abiCoder assume anything in quotes as `true`
  114. if (type === 'bool' && args[i] === 'false') {
  115. args[i] = false;
  116. }
  117. types.push(type.indexOf('tuple') === 0 ? buildFullTypeDefinition(funABI.inputs[i]) : type);
  118. if (args.length < types.length) {
  119. args.push('');
  120. }
  121. }
  122. }
  123. encodeArgs(funABI.inputs, args);
  124. convertTypes(types);
  125. return abiCoder.encode(types, args);
  126. }
  127. export function decodeParamsV2ByABI(funABI: FunctionFragment | AbiInputsType, data: string | Uint8Array) {
  128. const convertTypeNames = (types: string[]) => {
  129. for (let i = 0; i < types.length; i++) {
  130. const type = types[i];
  131. if (/^trcToken/.test(type)) types[i] = type.replace(/^trcToken/, 'uint256');
  132. }
  133. };
  134. const convertAddresses = (addrArr: string | string[]) => {
  135. if (Array.isArray(addrArr)) {
  136. addrArr.forEach((addrs, i) => {
  137. addrArr[i] = convertAddresses(addrs) as string;
  138. });
  139. return addrArr;
  140. } else {
  141. return TronWeb.address.toHex(addrArr);
  142. }
  143. };
  144. const mapTuple = (components: ReadonlyArray<AbiParamsCommon>, args: string[] | string[][], dimension: number) => {
  145. if (dimension > 1) {
  146. if (args.length) {
  147. args.forEach((arg) => {
  148. mapTuple(components, arg as string[], dimension - 1);
  149. });
  150. }
  151. } else {
  152. if (args.length && dimension) {
  153. args.forEach((arg) => {
  154. decodeResult(components, arg as string[]);
  155. });
  156. }
  157. }
  158. };
  159. const buildFullTypeNameDefinition = (typeDef: AbiParamsCommon): string => {
  160. const name = typeDef.name ? ` ${typeDef.name}` : '';
  161. if (typeDef && typeDef.type.indexOf('tuple') === 0 && typeDef.components) {
  162. const innerTypes = typeDef.components.map((innerType) => {
  163. return buildFullTypeNameDefinition(innerType);
  164. });
  165. return `tuple(${innerTypes.join(',')})${extractSize(typeDef.type)}${name}`;
  166. }
  167. if (/trcToken/.test(typeDef.type)) return typeDef.type.replace(/trcToken/, 'uint256') + name;
  168. return typeDef.type + name;
  169. };
  170. const decodeResult = (outputs: ReadonlyArray<AbiParamsCommon>, result: any[]) => {
  171. if (outputs.length)
  172. outputs.forEach((output, i) => {
  173. const { type, name } = output;
  174. if (result[i]) {
  175. if (type === 'address') {
  176. result[i] = TronWeb.address.toHex(result[i]);
  177. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  178. //@ts-ignore
  179. if (name) result[name] = TronWeb.address.toHex(result[i]);
  180. } else if (type.match(/^([^\x5b]*)(\x5b|$)/)![0] === 'address[') {
  181. convertAddresses(result[i]);
  182. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  183. //@ts-ignore
  184. if (name) result[name] = convertAddresses(result[i]);
  185. } else if (type.indexOf('tuple') === 0) {
  186. if (extractSize(type)) {
  187. const dimension = extractArrayDim(type);
  188. mapTuple(output.components!, result[i], dimension);
  189. } else decodeResult(output.components!, result[i]);
  190. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  191. //@ts-ignore
  192. if (name) result[name] = result[i];
  193. } else {
  194. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  195. //@ts-ignore
  196. if (name) result[name] = result[i];
  197. }
  198. } else {
  199. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  200. //@ts-ignore
  201. if (name) result[name] = result[i];
  202. }
  203. });
  204. };
  205. // Only decode if there supposed to be fields
  206. if ('outputs' in funABI && funABI.outputs && funABI.outputs.length > 0) {
  207. const outputTypes: any[] = [];
  208. for (let i = 0; i < funABI.outputs.length; i++) {
  209. const type = funABI.outputs[i].type;
  210. const name = funABI.outputs[i].name ? ` ${funABI.outputs[i].name}` : '';
  211. outputTypes.push(type.indexOf('tuple') === 0 ? buildFullTypeNameDefinition(funABI.outputs[i]) : type + name);
  212. }
  213. convertTypeNames(outputTypes);
  214. if (!data || !data.length) data = new Uint8Array(32 * funABI.outputs.length); // ensuring the data is at least filled by 0 cause `AbiCoder` throws if there's not engouh data
  215. // decode data
  216. const decodeRes = abiCoder.decode(outputTypes, data);
  217. const decodeResCopy = decodeRes.toArray(true);
  218. decodeResult(funABI.outputs, decodeResCopy);
  219. return decodeResCopy;
  220. }
  221. return [];
  222. }