format.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * @_ignore
  3. */
  4. import { getAddress, getCreateAddress } from "../address/index.js";
  5. import { Signature } from "../crypto/index.js"
  6. import { accessListify } from "../transaction/index.js";
  7. import {
  8. getBigInt, getNumber, hexlify, isHexString, zeroPadValue,
  9. assert, assertArgument
  10. } from "../utils/index.js";
  11. import type {
  12. BlockParams, LogParams,
  13. TransactionReceiptParams, TransactionResponseParams,
  14. } from "./formatting.js";
  15. const BN_0 = BigInt(0);
  16. export type FormatFunc = (value: any) => any;
  17. export function allowNull(format: FormatFunc, nullValue?: any): FormatFunc {
  18. return (function(value: any) {
  19. if (value == null) { return nullValue; }
  20. return format(value);
  21. });
  22. }
  23. export function arrayOf(format: FormatFunc, allowNull?: boolean): FormatFunc {
  24. return ((array: any) => {
  25. if (allowNull && array == null) { return null; }
  26. if (!Array.isArray(array)) { throw new Error("not an array"); }
  27. return array.map((i) => format(i));
  28. });
  29. }
  30. // Requires an object which matches a fleet of other formatters
  31. // Any FormatFunc may return `undefined` to have the value omitted
  32. // from the result object. Calls preserve `this`.
  33. export function object(format: Record<string, FormatFunc>, altNames?: Record<string, Array<string>>): FormatFunc {
  34. return ((value: any) => {
  35. const result: any = { };
  36. for (const key in format) {
  37. let srcKey = key;
  38. if (altNames && key in altNames && !(srcKey in value)) {
  39. for (const altKey of altNames[key]) {
  40. if (altKey in value) {
  41. srcKey = altKey;
  42. break;
  43. }
  44. }
  45. }
  46. try {
  47. const nv = format[key](value[srcKey]);
  48. if (nv !== undefined) { result[key] = nv; }
  49. } catch (error) {
  50. const message = (error instanceof Error) ? error.message: "not-an-error";
  51. assert(false, `invalid value for value.${ key } (${ message })`, "BAD_DATA", { value })
  52. }
  53. }
  54. return result;
  55. });
  56. }
  57. export function formatBoolean(value: any): boolean {
  58. switch (value) {
  59. case true: case "true":
  60. return true;
  61. case false: case "false":
  62. return false;
  63. }
  64. assertArgument(false, `invalid boolean; ${ JSON.stringify(value) }`, "value", value);
  65. }
  66. export function formatData(value: string): string {
  67. assertArgument(isHexString(value, true), "invalid data", "value", value);
  68. return value;
  69. }
  70. export function formatHash(value: any): string {
  71. assertArgument(isHexString(value, 32), "invalid hash", "value", value);
  72. return value;
  73. }
  74. export function formatUint256(value: any): string {
  75. if (!isHexString(value)) {
  76. throw new Error("invalid uint256");
  77. }
  78. return zeroPadValue(value, 32);
  79. }
  80. const _formatLog = object({
  81. address: getAddress,
  82. blockHash: formatHash,
  83. blockNumber: getNumber,
  84. data: formatData,
  85. index: getNumber,
  86. removed: allowNull(formatBoolean, false),
  87. topics: arrayOf(formatHash),
  88. transactionHash: formatHash,
  89. transactionIndex: getNumber,
  90. }, {
  91. index: [ "logIndex" ]
  92. });
  93. export function formatLog(value: any): LogParams {
  94. return _formatLog(value);
  95. }
  96. const _formatBlock = object({
  97. hash: allowNull(formatHash),
  98. parentHash: formatHash,
  99. parentBeaconBlockRoot: allowNull(formatHash, null),
  100. number: getNumber,
  101. timestamp: getNumber,
  102. nonce: allowNull(formatData),
  103. difficulty: getBigInt,
  104. gasLimit: getBigInt,
  105. gasUsed: getBigInt,
  106. stateRoot: allowNull(formatHash, null),
  107. receiptsRoot: allowNull(formatHash, null),
  108. blobGasUsed: allowNull(getBigInt, null),
  109. excessBlobGas: allowNull(getBigInt, null),
  110. miner: allowNull(getAddress),
  111. prevRandao: allowNull(formatHash, null),
  112. extraData: formatData,
  113. baseFeePerGas: allowNull(getBigInt)
  114. }, {
  115. prevRandao: [ "mixHash" ]
  116. });
  117. export function formatBlock(value: any): BlockParams {
  118. const result = _formatBlock(value);
  119. result.transactions = value.transactions.map((tx: string | TransactionResponseParams) => {
  120. if (typeof(tx) === "string") { return tx; }
  121. return formatTransactionResponse(tx);
  122. });
  123. return result;
  124. }
  125. const _formatReceiptLog = object({
  126. transactionIndex: getNumber,
  127. blockNumber: getNumber,
  128. transactionHash: formatHash,
  129. address: getAddress,
  130. topics: arrayOf(formatHash),
  131. data: formatData,
  132. index: getNumber,
  133. blockHash: formatHash,
  134. }, {
  135. index: [ "logIndex" ]
  136. });
  137. export function formatReceiptLog(value: any): LogParams {
  138. return _formatReceiptLog(value);
  139. }
  140. const _formatTransactionReceipt = object({
  141. to: allowNull(getAddress, null),
  142. from: allowNull(getAddress, null),
  143. contractAddress: allowNull(getAddress, null),
  144. // should be allowNull(hash), but broken-EIP-658 support is handled in receipt
  145. index: getNumber,
  146. root: allowNull(hexlify),
  147. gasUsed: getBigInt,
  148. blobGasUsed: allowNull(getBigInt, null),
  149. logsBloom: allowNull(formatData),
  150. blockHash: formatHash,
  151. hash: formatHash,
  152. logs: arrayOf(formatReceiptLog),
  153. blockNumber: getNumber,
  154. //confirmations: allowNull(getNumber, null),
  155. cumulativeGasUsed: getBigInt,
  156. effectiveGasPrice: allowNull(getBigInt),
  157. blobGasPrice: allowNull(getBigInt, null),
  158. status: allowNull(getNumber),
  159. type: allowNull(getNumber, 0)
  160. }, {
  161. effectiveGasPrice: [ "gasPrice" ],
  162. hash: [ "transactionHash" ],
  163. index: [ "transactionIndex" ],
  164. });
  165. export function formatTransactionReceipt(value: any): TransactionReceiptParams {
  166. return _formatTransactionReceipt(value);
  167. }
  168. export function formatTransactionResponse(value: any): TransactionResponseParams {
  169. // Some clients (TestRPC) do strange things like return 0x0 for the
  170. // 0 address; correct this to be a real address
  171. if (value.to && getBigInt(value.to) === BN_0) {
  172. value.to = "0x0000000000000000000000000000000000000000";
  173. }
  174. const result = object({
  175. hash: formatHash,
  176. // Some nodes do not return this, usually test nodes (like Ganache)
  177. index: allowNull(getNumber, undefined),
  178. type: (value: any) => {
  179. if (value === "0x" || value == null) { return 0; }
  180. return getNumber(value);
  181. },
  182. accessList: allowNull(accessListify, null),
  183. blobVersionedHashes: allowNull(arrayOf(formatHash, true), null),
  184. blockHash: allowNull(formatHash, null),
  185. blockNumber: allowNull(getNumber, null),
  186. transactionIndex: allowNull(getNumber, null),
  187. from: getAddress,
  188. // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set
  189. gasPrice: allowNull(getBigInt),
  190. maxPriorityFeePerGas: allowNull(getBigInt),
  191. maxFeePerGas: allowNull(getBigInt),
  192. maxFeePerBlobGas: allowNull(getBigInt, null),
  193. gasLimit: getBigInt,
  194. to: allowNull(getAddress, null),
  195. value: getBigInt,
  196. nonce: getNumber,
  197. data: formatData,
  198. creates: allowNull(getAddress, null),
  199. chainId: allowNull(getBigInt, null)
  200. }, {
  201. data: [ "input" ],
  202. gasLimit: [ "gas" ],
  203. index: [ "transactionIndex" ]
  204. })(value);
  205. // If to and creates are empty, populate the creates from the value
  206. if (result.to == null && result.creates == null) {
  207. result.creates = getCreateAddress(result);
  208. }
  209. // @TODO: Check fee data
  210. // Add an access list to supported transaction types
  211. if ((value.type === 1 || value.type === 2) && value.accessList == null) {
  212. result.accessList = [ ];
  213. }
  214. // Compute the signature
  215. if (value.signature) {
  216. result.signature = Signature.from(value.signature);
  217. } else {
  218. result.signature = Signature.from(value);
  219. }
  220. // Some backends omit ChainId on legacy transactions, but we can compute it
  221. if (result.chainId == null) {
  222. const chainId = result.signature.legacyChainId;
  223. if (chainId != null) { result.chainId = chainId; }
  224. }
  225. // @TODO: check chainID
  226. /*
  227. if (value.chainId != null) {
  228. let chainId = value.chainId;
  229. if (isHexString(chainId)) {
  230. chainId = BigNumber.from(chainId).toNumber();
  231. }
  232. result.chainId = chainId;
  233. } else {
  234. let chainId = value.networkId;
  235. // geth-etc returns chainId
  236. if (chainId == null && result.v == null) {
  237. chainId = value.chainId;
  238. }
  239. if (isHexString(chainId)) {
  240. chainId = BigNumber.from(chainId).toNumber();
  241. }
  242. if (typeof(chainId) !== "number" && result.v != null) {
  243. chainId = (result.v - 35) / 2;
  244. if (chainId < 0) { chainId = 0; }
  245. chainId = parseInt(chainId);
  246. }
  247. if (typeof(chainId) !== "number") { chainId = 0; }
  248. result.chainId = chainId;
  249. }
  250. */
  251. // 0x0000... should actually be null
  252. if (result.blockHash && getBigInt(result.blockHash) === BN_0) {
  253. result.blockHash = null;
  254. }
  255. return result;
  256. }