@latticexyz/common 2.2.22-ca7a36a114ba65468662dbeef343129fa60f04eb → 2.2.22-d59c81524363756c6fd68dc696e996d8675eb095
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chains.d.ts +7 -5
- package/dist/{chunk-NFWCLD5I.js → chunk-ETXWXV5T.js} +14 -1
- package/dist/chunk-ETXWXV5T.js.map +1 -0
- package/dist/codegen.d.ts +12 -9
- package/dist/codegen.js +84 -46
- package/dist/codegen.js.map +1 -1
- package/dist/internal.d.ts +8 -1
- package/dist/internal.js +371 -2
- package/dist/internal.js.map +1 -1
- package/dist/utils.js +2 -4
- package/package.json +3 -3
- package/dist/chunk-CHXZROA7.js +0 -16
- package/dist/chunk-CHXZROA7.js.map +0 -1
- package/dist/chunk-NFWCLD5I.js.map +0 -1
package/dist/chains.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import * as viem_chains from 'viem/chains';
|
|
2
2
|
import { Chain } from 'viem/chains';
|
|
3
3
|
import * as viem from 'viem';
|
|
4
|
-
import * as viem_experimental from 'viem/experimental';
|
|
5
4
|
import * as viem_op_stack from 'viem/op-stack';
|
|
6
5
|
|
|
7
6
|
type MUDChain = Chain & {
|
|
@@ -36,6 +35,7 @@ declare const mudFoundry: {
|
|
|
36
35
|
multicall3?: viem.ChainContract | undefined;
|
|
37
36
|
universalSignatureVerifier?: viem.ChainContract | undefined;
|
|
38
37
|
} | undefined;
|
|
38
|
+
readonly ensTlds?: readonly string[] | undefined;
|
|
39
39
|
readonly id: 31337;
|
|
40
40
|
readonly name: "Foundry";
|
|
41
41
|
readonly nativeCurrency: {
|
|
@@ -106,6 +106,7 @@ declare const redstone: {
|
|
|
106
106
|
readonly address: "0x4200000000000000000000000000000000000016";
|
|
107
107
|
};
|
|
108
108
|
};
|
|
109
|
+
readonly ensTlds?: readonly string[] | undefined;
|
|
109
110
|
readonly id: 690;
|
|
110
111
|
readonly name: "Redstone";
|
|
111
112
|
readonly nativeCurrency: {
|
|
@@ -312,7 +313,7 @@ declare const redstone: {
|
|
|
312
313
|
value: bigint;
|
|
313
314
|
yParity: number;
|
|
314
315
|
accessList: viem.AccessList;
|
|
315
|
-
authorizationList:
|
|
316
|
+
authorizationList: viem.SignedAuthorizationList<number>;
|
|
316
317
|
blobVersionedHashes?: undefined;
|
|
317
318
|
chainId: number;
|
|
318
319
|
type: "eip7702";
|
|
@@ -419,6 +420,7 @@ declare const garnet: {
|
|
|
419
420
|
readonly address: "0x4200000000000000000000000000000000000016";
|
|
420
421
|
};
|
|
421
422
|
};
|
|
423
|
+
readonly ensTlds?: readonly string[] | undefined;
|
|
422
424
|
readonly id: 17069;
|
|
423
425
|
readonly name: "Garnet Testnet";
|
|
424
426
|
readonly nativeCurrency: {
|
|
@@ -619,7 +621,7 @@ declare const garnet: {
|
|
|
619
621
|
value: bigint;
|
|
620
622
|
yParity: number;
|
|
621
623
|
accessList: viem.AccessList;
|
|
622
|
-
authorizationList:
|
|
624
|
+
authorizationList: viem.SignedAuthorizationList<number>;
|
|
623
625
|
blobVersionedHashes?: undefined;
|
|
624
626
|
chainId: number;
|
|
625
627
|
type: "eip7702";
|
|
@@ -923,7 +925,7 @@ declare const rhodolite: {
|
|
|
923
925
|
value: bigint;
|
|
924
926
|
yParity: number;
|
|
925
927
|
accessList: viem.AccessList;
|
|
926
|
-
authorizationList:
|
|
928
|
+
authorizationList: viem.SignedAuthorizationList<number>;
|
|
927
929
|
blobVersionedHashes?: undefined;
|
|
928
930
|
chainId: number;
|
|
929
931
|
type: "eip7702";
|
|
@@ -1216,7 +1218,7 @@ declare const pyrope: {
|
|
|
1216
1218
|
value: bigint;
|
|
1217
1219
|
yParity: number;
|
|
1218
1220
|
accessList: viem.AccessList;
|
|
1219
|
-
authorizationList:
|
|
1221
|
+
authorizationList: viem.SignedAuthorizationList<number>;
|
|
1220
1222
|
blobVersionedHashes?: undefined;
|
|
1221
1223
|
chainId: number;
|
|
1222
1224
|
type: "eip7702";
|
|
@@ -82,6 +82,18 @@ function unique(values) {
|
|
|
82
82
|
return Array.from(new Set(values));
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
// src/utils/uniqueBy.ts
|
|
86
|
+
function uniqueBy(values, getKey) {
|
|
87
|
+
const map = /* @__PURE__ */ new Map();
|
|
88
|
+
for (const value of values) {
|
|
89
|
+
const key = getKey(value);
|
|
90
|
+
if (!map.has(key)) {
|
|
91
|
+
map.set(key, value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return Array.from(map.values());
|
|
95
|
+
}
|
|
96
|
+
|
|
85
97
|
// src/utils/wait.ts
|
|
86
98
|
function wait(ms) {
|
|
87
99
|
return new Promise((resolve) => setTimeout(() => resolve(), ms));
|
|
@@ -113,7 +125,8 @@ export {
|
|
|
113
125
|
iteratorToArray,
|
|
114
126
|
mapObject,
|
|
115
127
|
unique,
|
|
128
|
+
uniqueBy,
|
|
116
129
|
wait,
|
|
117
130
|
waitForIdle
|
|
118
131
|
};
|
|
119
|
-
//# sourceMappingURL=chunk-
|
|
132
|
+
//# sourceMappingURL=chunk-ETXWXV5T.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/assertExhaustive.ts","../src/utils/bigIntMax.ts","../src/utils/bigIntMin.ts","../src/utils/bigIntSort.ts","../src/utils/chunk.ts","../src/utils/groupBy.ts","../src/utils/identity.ts","../src/utils/includes.ts","../src/utils/indent.ts","../src/utils/isDefined.ts","../src/utils/isNotNull.ts","../src/utils/iteratorToArray.ts","../src/utils/mapObject.ts","../src/utils/unique.ts","../src/utils/uniqueBy.ts","../src/utils/wait.ts","../src/utils/waitForIdle.ts"],"sourcesContent":["export function assertExhaustive(value: never, message?: string): never {\n throw new Error(message ?? `Unexpected value: ${value}`);\n}\n","export function bigIntMax(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e > m ? e : m));\n}\n","export function bigIntMin(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e < m ? e : m));\n}\n","export function bigIntSort(a: bigint, b: bigint): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","export function* chunk<T>(arr: readonly T[], n: number): Generator<readonly T[], void> {\n for (let i = 0; i < arr.length; i += n) {\n yield arr.slice(i, i + n);\n }\n}\n","export function groupBy<value, key>(\n values: readonly value[],\n getKey: (value: value) => key,\n): Map<key, readonly value[]> {\n const map = new Map<key, readonly value[]>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) map.set(key, []);\n (map.get(key) as value[]).push(value);\n }\n return map;\n}\n","export function identity<T>(value: T): T {\n return value;\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function includes<item>(items: item[], value: any): value is item {\n return items.includes(value);\n}\n","export function indent(message: string, indentation = \" \"): string {\n return message.replaceAll(/(^|\\n)/g, `$1${indentation}`);\n}\n","export function isDefined<T>(argument: T | undefined): argument is T {\n return argument !== undefined;\n}\n","export function isNotNull<T>(argument: T | null): argument is T {\n return argument !== null;\n}\n","export async function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<readonly T[]> {\n const items: T[] = [];\n for await (const item of iterator) {\n items.push(item);\n }\n return items;\n}\n","/**\n * Map each key of a source object via a given valueMap function\n */\nexport function mapObject<\n Source extends Record<string | number | symbol, unknown>,\n Target extends { [key in keyof Source]: unknown },\n>(source: Source, valueMap: (value: Source[typeof key], key: keyof Source) => Target[typeof key]): Target {\n return Object.fromEntries(\n Object.entries(source).map(([key, value]) => [key, valueMap(value as Source[keyof Source], key)]),\n ) as Target;\n}\n","export function unique<value>(values: readonly value[]): readonly value[] {\n return Array.from(new Set(values));\n}\n","export function uniqueBy<value, key>(values: readonly value[], getKey: (value: value) => key): readonly value[] {\n const map = new Map<key, value>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) {\n map.set(key, value);\n }\n }\n return Array.from(map.values());\n}\n","export function wait(ms: number): Promise<void> {\n return new Promise<void>((resolve) => setTimeout(() => resolve(), ms));\n}\n","export function waitForIdle(): Promise<void> {\n return new Promise<void>((resolve) => {\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(() => resolve(), 1);\n }\n });\n}\n"],"mappings":";AAAO,SAAS,iBAAiB,OAAc,SAAyB;AACtE,QAAM,IAAI,MAAM,WAAW,qBAAqB,KAAK,EAAE;AACzD;;;ACFO,SAAS,aAAa,MAAwB;AACnD,SAAO,KAAK,OAAO,CAAC,GAAG,MAAO,IAAI,IAAI,IAAI,CAAE;AAC9C;;;ACFO,SAAS,aAAa,MAAwB;AACnD,SAAO,KAAK,OAAO,CAAC,GAAG,MAAO,IAAI,IAAI,IAAI,CAAE;AAC9C;;;ACFO,SAAS,WAAW,GAAW,GAAuB;AAC3D,SAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAClC;;;ACFO,UAAU,MAAS,KAAmB,GAA0C;AACrF,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;AACtC,UAAM,IAAI,MAAM,GAAG,IAAI,CAAC;AAAA,EAC1B;AACF;;;ACJO,SAAS,QACd,QACA,QAC4B;AAC5B,QAAM,MAAM,oBAAI,IAA2B;AAC3C,aAAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,CAAC,IAAI,IAAI,GAAG,EAAG,KAAI,IAAI,KAAK,CAAC,CAAC;AAClC,IAAC,IAAI,IAAI,GAAG,EAAc,KAAK,KAAK;AAAA,EACtC;AACA,SAAO;AACT;;;ACXO,SAAS,SAAY,OAAa;AACvC,SAAO;AACT;;;ACDO,SAAS,SAAe,OAAe,OAA2B;AACvE,SAAO,MAAM,SAAS,KAAK;AAC7B;;;ACHO,SAAS,OAAO,SAAiB,cAAc,MAAc;AAClE,SAAO,QAAQ,WAAW,WAAW,KAAK,WAAW,EAAE;AACzD;;;ACFO,SAAS,UAAa,UAAwC;AACnE,SAAO,aAAa;AACtB;;;ACFO,SAAS,UAAa,UAAmC;AAC9D,SAAO,aAAa;AACtB;;;ACFA,eAAsB,gBAAmB,UAAmD;AAC1F,QAAM,QAAa,CAAC;AACpB,mBAAiB,QAAQ,UAAU;AACjC,UAAM,KAAK,IAAI;AAAA,EACjB;AACA,SAAO;AACT;;;ACHO,SAAS,UAGd,QAAgB,UAAwF;AACxG,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,SAAS,OAA+B,GAAG,CAAC,CAAC;AAAA,EAClG;AACF;;;ACVO,SAAS,OAAc,QAA4C;AACxE,SAAO,MAAM,KAAK,IAAI,IAAI,MAAM,CAAC;AACnC;;;ACFO,SAAS,SAAqB,QAA0B,QAAiD;AAC9G,QAAM,MAAM,oBAAI,IAAgB;AAChC,aAAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,CAAC,IAAI,IAAI,GAAG,GAAG;AACjB,UAAI,IAAI,KAAK,KAAK;AAAA,IACpB;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC;AAChC;;;ACTO,SAAS,KAAK,IAA2B;AAC9C,SAAO,IAAI,QAAc,CAAC,YAAY,WAAW,MAAM,QAAQ,GAAG,EAAE,CAAC;AACvE;;;ACFO,SAAS,cAA6B;AAC3C,SAAO,IAAI,QAAc,CAAC,YAAY;AACpC,QAAI,OAAO,wBAAwB,aAAa;AAC9C,0BAAoB,MAAM,QAAQ,CAAC;AAAA,IACrC,OAAO;AACL,iBAAW,MAAM,QAAQ,GAAG,CAAC;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":[]}
|
package/dist/codegen.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Hex } from 'viem';
|
|
2
2
|
import { Abi } from 'abitype';
|
|
3
3
|
import { SchemaType } from '@latticexyz/schema-type/deprecated';
|
|
4
|
-
import { SourceUnit, ContractDefinition } from '@solidity-parser/parser/dist/src/ast-types';
|
|
5
4
|
|
|
6
5
|
declare module "prettier-plugin-solidity" {}
|
|
7
6
|
|
|
@@ -168,6 +167,11 @@ declare function renderTypeHelpers(options: {
|
|
|
168
167
|
|
|
169
168
|
declare const schemaTypesToRecsTypeStrings: Record<SchemaType, string>;
|
|
170
169
|
|
|
170
|
+
interface SymbolImport {
|
|
171
|
+
symbol: string;
|
|
172
|
+
path: string;
|
|
173
|
+
}
|
|
174
|
+
|
|
171
175
|
interface ContractInterfaceFunction {
|
|
172
176
|
name: string;
|
|
173
177
|
parameters: string[];
|
|
@@ -178,10 +182,6 @@ interface ContractInterfaceError {
|
|
|
178
182
|
name: string;
|
|
179
183
|
parameters: string[];
|
|
180
184
|
}
|
|
181
|
-
interface SymbolImport {
|
|
182
|
-
symbol: string;
|
|
183
|
-
path: string;
|
|
184
|
-
}
|
|
185
185
|
/**
|
|
186
186
|
* Parse the contract data to get the functions necessary to generate an interface,
|
|
187
187
|
* and symbols to import from the original contract.
|
|
@@ -194,7 +194,6 @@ declare function contractToInterface(source: string, contractName: string): {
|
|
|
194
194
|
errors: ContractInterfaceError[];
|
|
195
195
|
symbolImports: SymbolImport[];
|
|
196
196
|
};
|
|
197
|
-
declare function findContractNode(ast: SourceUnit, contractName: string): ContractDefinition | undefined;
|
|
198
197
|
|
|
199
198
|
/**
|
|
200
199
|
* Formats solidity code using prettier
|
|
@@ -212,11 +211,11 @@ declare function formatTypescript(content: string): Promise<string>;
|
|
|
212
211
|
|
|
213
212
|
/**
|
|
214
213
|
* Formats solidity code using prettier and write it to a file
|
|
215
|
-
* @param
|
|
214
|
+
* @param content solidity code
|
|
216
215
|
* @param fullOutputPath full path to the output file
|
|
217
216
|
* @param logPrefix prefix for debug logs
|
|
218
217
|
*/
|
|
219
|
-
declare function formatAndWriteSolidity(
|
|
218
|
+
declare function formatAndWriteSolidity(content: string, fullOutputPath: string, logPrefix: string): Promise<void>;
|
|
220
219
|
/**
|
|
221
220
|
* Formats typescript code using prettier and write it to a file
|
|
222
221
|
* @param output typescript code
|
|
@@ -225,4 +224,8 @@ declare function formatAndWriteSolidity(output: string, fullOutputPath: string,
|
|
|
225
224
|
*/
|
|
226
225
|
declare function formatAndWriteTypescript(output: string, fullOutputPath: string, logPrefix: string): Promise<void>;
|
|
227
226
|
|
|
228
|
-
|
|
227
|
+
declare function parseSystem(source: string, contractName: string): undefined | {
|
|
228
|
+
contractType: "contract" | "abstract";
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
export { type AbiToInterfaceOptions, type ContractInterfaceError, type ContractInterfaceFunction, type ImportDatum, type RenderDynamicField, type RenderEnum, type RenderField, type RenderFieldTypeWrappingData, type RenderKeyTuple, type RenderStaticField, type RenderType, type StaticResourceData, abiToInterface, contractToInterface, formatAndWriteSolidity, formatAndWriteTypescript, formatSolidity, formatTypescript, getLeftPaddingBits, isLeftAligned, parseSystem, renderArguments, renderCommonData, renderEnums, renderImportPath, renderImports, renderList, renderTableId, renderTypeHelpers, renderValueTypeToBytes32, renderWithFieldSuffix, renderWithStore, renderedSolidityHeader, schemaTypesToRecsTypeStrings };
|
package/dist/codegen.js
CHANGED
|
@@ -10,8 +10,7 @@ import {
|
|
|
10
10
|
} from "./chunk-GRGLAPN2.js";
|
|
11
11
|
import {
|
|
12
12
|
isDefined
|
|
13
|
-
} from "./chunk-
|
|
14
|
-
import "./chunk-CHXZROA7.js";
|
|
13
|
+
} from "./chunk-ETXWXV5T.js";
|
|
15
14
|
|
|
16
15
|
// src/codegen/render-solidity/abiToInterface.ts
|
|
17
16
|
import { formatAbiItem, formatAbiParameter } from "abitype";
|
|
@@ -520,7 +519,47 @@ var schemaTypesToRecsTypeStrings = {
|
|
|
520
519
|
};
|
|
521
520
|
|
|
522
521
|
// src/codegen/utils/contractToInterface.ts
|
|
523
|
-
import { parse, visit } from "@solidity-parser/parser";
|
|
522
|
+
import { parse, visit as visit3 } from "@solidity-parser/parser";
|
|
523
|
+
|
|
524
|
+
// src/codegen/utils/findContractNode.ts
|
|
525
|
+
import { visit } from "@solidity-parser/parser";
|
|
526
|
+
function findContractNode(ast, contractName) {
|
|
527
|
+
let contract = void 0;
|
|
528
|
+
visit(ast, {
|
|
529
|
+
ContractDefinition(node) {
|
|
530
|
+
if (node.name === contractName) {
|
|
531
|
+
contract = node;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
return contract;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/codegen/utils/findSymbolImport.ts
|
|
539
|
+
import { visit as visit2 } from "@solidity-parser/parser";
|
|
540
|
+
function findSymbolImport(ast, symbol) {
|
|
541
|
+
let symbolImport;
|
|
542
|
+
visit2(ast, {
|
|
543
|
+
ImportDirective({ path: path3, symbolAliases }) {
|
|
544
|
+
if (symbolAliases) {
|
|
545
|
+
for (const symbolAndAlias of symbolAliases) {
|
|
546
|
+
const symbolAlias = symbolAndAlias[1] ?? symbolAndAlias[0];
|
|
547
|
+
if (symbol === symbolAlias) {
|
|
548
|
+
symbolImport = {
|
|
549
|
+
// always use the original symbol for interface imports
|
|
550
|
+
symbol: symbolAndAlias[0],
|
|
551
|
+
path: path3
|
|
552
|
+
};
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
return symbolImport;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// src/codegen/utils/contractToInterface.ts
|
|
524
563
|
function contractToInterface(source, contractName) {
|
|
525
564
|
const ast = parse(source);
|
|
526
565
|
const contractNode = findContractNode(ast, contractName);
|
|
@@ -530,7 +569,7 @@ function contractToInterface(source, contractName) {
|
|
|
530
569
|
if (!contractNode) {
|
|
531
570
|
throw new MUDError(`Contract not found: ${contractName}`);
|
|
532
571
|
}
|
|
533
|
-
|
|
572
|
+
visit3(contractNode, {
|
|
534
573
|
FunctionDefinition({
|
|
535
574
|
name,
|
|
536
575
|
visibility,
|
|
@@ -580,17 +619,6 @@ function contractToInterface(source, contractName) {
|
|
|
580
619
|
symbolImports
|
|
581
620
|
};
|
|
582
621
|
}
|
|
583
|
-
function findContractNode(ast, contractName) {
|
|
584
|
-
let contract = void 0;
|
|
585
|
-
visit(ast, {
|
|
586
|
-
ContractDefinition(node) {
|
|
587
|
-
if (node.name === contractName) {
|
|
588
|
-
contract = node;
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
});
|
|
592
|
-
return contract;
|
|
593
|
-
}
|
|
594
622
|
function parseParameter({ name, typeName, storageLocation }) {
|
|
595
623
|
let typedNameWithLocation = "";
|
|
596
624
|
const { name: flattenedTypeName, stateMutability } = flattenTypeName(typeName);
|
|
@@ -655,33 +683,11 @@ function typeNameToSymbols(typeName) {
|
|
|
655
683
|
}
|
|
656
684
|
}
|
|
657
685
|
function symbolsToImports(ast, symbols) {
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
if (symbolAliases) {
|
|
664
|
-
for (const symbolAndAlias of symbolAliases) {
|
|
665
|
-
const symbolAlias = symbolAndAlias[1] || symbolAndAlias[0];
|
|
666
|
-
if (symbol === symbolAlias) {
|
|
667
|
-
symbolImport = {
|
|
668
|
-
// always use the original symbol for interface imports
|
|
669
|
-
symbol: symbolAndAlias[0],
|
|
670
|
-
path: path3
|
|
671
|
-
};
|
|
672
|
-
return;
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
});
|
|
678
|
-
if (symbolImport) {
|
|
679
|
-
imports.push(symbolImport);
|
|
680
|
-
} else {
|
|
681
|
-
throw new MUDError(`Symbol "${symbol}" has no explicit import`);
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
return imports;
|
|
686
|
+
return symbols.map((symbol) => {
|
|
687
|
+
const symbolImport = findSymbolImport(ast, symbol);
|
|
688
|
+
if (!symbolImport) throw new MUDError(`Symbol "${symbol}" has no explicit import`);
|
|
689
|
+
return symbolImport;
|
|
690
|
+
});
|
|
685
691
|
}
|
|
686
692
|
|
|
687
693
|
// src/codegen/utils/format.ts
|
|
@@ -731,10 +737,15 @@ debug2.log = console.debug.bind(console);
|
|
|
731
737
|
error.log = console.error.bind(console);
|
|
732
738
|
|
|
733
739
|
// src/codegen/utils/formatAndWrite.ts
|
|
734
|
-
async function formatAndWriteSolidity(
|
|
735
|
-
|
|
740
|
+
async function formatAndWriteSolidity(content, fullOutputPath, logPrefix) {
|
|
741
|
+
let output = content;
|
|
742
|
+
try {
|
|
743
|
+
output = await formatSolidity(output);
|
|
744
|
+
} catch (e) {
|
|
745
|
+
error(`Error while attempting to format ${fullOutputPath}`, e);
|
|
746
|
+
}
|
|
736
747
|
await fs.mkdir(path2.dirname(fullOutputPath), { recursive: true });
|
|
737
|
-
await fs.writeFile(fullOutputPath,
|
|
748
|
+
await fs.writeFile(fullOutputPath, output);
|
|
738
749
|
debug2(`${logPrefix}: ${fullOutputPath}`);
|
|
739
750
|
}
|
|
740
751
|
async function formatAndWriteTypescript(output, fullOutputPath, logPrefix) {
|
|
@@ -743,16 +754,43 @@ async function formatAndWriteTypescript(output, fullOutputPath, logPrefix) {
|
|
|
743
754
|
await fs.writeFile(fullOutputPath, formattedOutput);
|
|
744
755
|
debug2(`${logPrefix}: ${fullOutputPath}`);
|
|
745
756
|
}
|
|
757
|
+
|
|
758
|
+
// src/codegen/utils/parseSystem.ts
|
|
759
|
+
import { parse as parse2, visit as visit4 } from "@solidity-parser/parser";
|
|
760
|
+
var baseSystemName = "System";
|
|
761
|
+
var baseSystemPath = "@latticexyz/world/src/System.sol";
|
|
762
|
+
function parseSystem(source, contractName) {
|
|
763
|
+
const ast = parse2(source);
|
|
764
|
+
const contractNode = findContractNode(ast, contractName);
|
|
765
|
+
if (!contractNode) return;
|
|
766
|
+
const contractType = contractNode.kind;
|
|
767
|
+
if (contractType !== "contract" && contractType !== "abstract") return;
|
|
768
|
+
const isSystem = (() => {
|
|
769
|
+
if (contractName.endsWith("System") && contractName !== baseSystemName) return true;
|
|
770
|
+
let extendsBaseSystem = false;
|
|
771
|
+
visit4(contractNode, {
|
|
772
|
+
InheritanceSpecifier(node) {
|
|
773
|
+
if (node.baseName.namePath === baseSystemName) {
|
|
774
|
+
extendsBaseSystem = true;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
});
|
|
778
|
+
return extendsBaseSystem && findSymbolImport(ast, baseSystemName)?.path === baseSystemPath;
|
|
779
|
+
})();
|
|
780
|
+
if (isSystem) {
|
|
781
|
+
return { contractType };
|
|
782
|
+
}
|
|
783
|
+
}
|
|
746
784
|
export {
|
|
747
785
|
abiToInterface,
|
|
748
786
|
contractToInterface,
|
|
749
|
-
findContractNode,
|
|
750
787
|
formatAndWriteSolidity,
|
|
751
788
|
formatAndWriteTypescript,
|
|
752
789
|
formatSolidity,
|
|
753
790
|
formatTypescript,
|
|
754
791
|
getLeftPaddingBits,
|
|
755
792
|
isLeftAligned,
|
|
793
|
+
parseSystem,
|
|
756
794
|
renderArguments,
|
|
757
795
|
renderCommonData,
|
|
758
796
|
renderEnums,
|
package/dist/codegen.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/codegen/render-solidity/abiToInterface.ts","../src/codegen/render-solidity/renderImportPath.ts","../src/codegen/render-solidity/common.ts","../src/codegen/render-solidity/renderEnums.ts","../src/codegen/render-solidity/renderTypeHelpers.ts","../src/codegen/render-typescript/schemaTypesToRecsTypeStrings.ts","../src/codegen/utils/contractToInterface.ts","../src/codegen/utils/format.ts","../src/codegen/utils/formatAndWrite.ts","../src/codegen/debug.ts"],"sourcesContent":["import { AbiParameter, Hex } from \"viem\";\nimport { Abi, AbiError, AbiFunction, formatAbiItem, formatAbiParameter } from \"abitype\";\nimport { renderedSolidityHeader } from \"./common\";\nimport { hexToResource } from \"../../hexToResource\";\n\nfunction formatParam(param: AbiParameter): string {\n // return param.type === \"string\" || param.type === \"bytes\" || param.type === \"tuple\" || param.type.endsWith(\"]\")\n // ? `${formatAbiParameter(param)} memory`\n // : formatAbiParameter(param);\n return formatAbiParameter(param);\n}\n\nfunction formatFunction(item: AbiFunction): string {\n const params = item.inputs.map(formatParam).join(\", \");\n const returns = item.outputs.map(formatParam).join(\", \");\n return `function ${item.name}(${params}) external${returns.length ? ` returns (${returns})` : \"\"}`;\n}\n\nfunction formatSystemId(systemId: Hex): string {\n const resource = hexToResource(systemId);\n return `\n // equivalent to \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: RESOURCE_SYSTEM });\\`\n ResourceId constant systemId = ResourceId.wrap(${systemId});\n `;\n}\n\nexport type AbiToInterfaceOptions = {\n name: string;\n systemId?: Hex;\n abi: Abi;\n};\n\nexport function abiToInterface({ name, systemId, abi }: AbiToInterfaceOptions): string {\n const imports = systemId ? [`{ ResourceId } from \"@latticexyz/store/src/ResourceId.sol\"`] : [];\n const errors = abi.filter((item): item is AbiError => item.type === \"error\");\n const functions = abi.filter((item): item is AbiFunction => item.type === \"function\");\n\n return `\n ${renderedSolidityHeader}\n\n ${imports.map((item) => `import ${item};`).join(\"\\n\")}\n\n ${systemId ? formatSystemId(systemId) : \"\"}\n\n interface ${name} {\n ${errors.map((item) => `${formatAbiItem(item)};`).join(\"\\n\")}\n\n ${functions\n .map((item) => {\n if ([...item.inputs, ...item.outputs].some((param) => param.type.startsWith(\"tuple\"))) {\n return `// TODO: replace tuple with struct\\n// ${formatFunction(item)};`;\n }\n return `${formatFunction(item)};`;\n })\n .join(\"\\n\")}\n }\n `;\n}\n","import path from \"node:path\";\n\n// This will probably break for backslash-escaped POSIX paths,\n// but we'll worry about that later.\nfunction winToPosix(segment: string): string {\n return segment.replaceAll(path.win32.sep, path.posix.sep);\n}\n\nexport function renderImportPath(basePath: string, ...segments: readonly string[]): string {\n // Solidity compiler expects POSIX paths\n const fullPath = path.posix\n .join(winToPosix(basePath), ...segments.map(winToPosix))\n // remove trailing slash\n .replace(/\\/$/, \"\");\n\n // `path.join` strips the leading `./`\n // so if we started with a relative path, make it relative again\n if (basePath.startsWith(\".\")) {\n const relativePath = \"./\" + fullPath;\n return relativePath.replace(/^(\\.\\/)+\\./, \".\");\n }\n\n return fullPath;\n}\n","import { ImportDatum, StaticResourceData, RenderKeyTuple, RenderType } from \"./types\";\nimport { resourceToHex } from \"../../resourceToHex\";\nimport { hexToResource } from \"../../hexToResource\";\nimport { renderImportPath } from \"./renderImportPath\";\nimport { isDefined } from \"../../utils\";\n\n/**\n * Common header for all codegenerated solidity files\n */\nexport const renderedSolidityHeader = `// SPDX-License-Identifier: MIT\npragma solidity >=0.8.24;\n\n/* Autogenerated file. Do not edit manually. */`;\n\n/**\n * Renders a list of lines\n */\nexport function renderList<T>(list: T[], renderItem: (item: T, index: number) => string): string {\n return internalRenderList(\"\", list, renderItem);\n}\n\n/**\n * Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones\n */\nexport function renderArguments(args: (string | undefined)[]): string {\n return args\n .filter(isDefined)\n .filter((arg) => arg !== \"\")\n .join(\", \");\n}\n\ninterface RenderedCommonData {\n /** `_tableId` variable prefixed with its type (empty string if absent) */\n _typedTableId: string;\n /** Comma-separated table key names prefixed with their types (empty string if 0 keys) */\n _typedKeyArgs: string;\n /** Definition and initialization of the dynamic `_keyTuple` bytes32 array */\n _keyTupleDefinition: string;\n}\n\n/**\n * Renders some solidity statements commonly used within table libraries\n * @param param0.staticResourceData static data about the table library\n * @param param0.keyTuple key tuple of the table library\n * @returns Rendered statement strings\n */\nexport function renderCommonData({\n staticResourceData,\n keyTuple,\n}: {\n staticResourceData?: StaticResourceData;\n keyTuple: RenderKeyTuple[];\n}): RenderedCommonData {\n // static resource means static tableId as well, and no tableId arguments\n const _typedTableId = staticResourceData ? \"\" : \"ResourceId _tableId\";\n const _typedKeyArgs = renderArguments(keyTuple.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n\n const _keyTupleDefinition = `\n bytes32[] memory _keyTuple = new bytes32[](${keyTuple.length});\n ${renderList(keyTuple, (key, index) => `_keyTuple[${index}] = ${renderValueTypeToBytes32(key.name, key)};`)}\n `;\n\n return {\n _typedTableId,\n _typedKeyArgs,\n _keyTupleDefinition,\n };\n}\n\n/**\n * Aggregates, deduplicates and renders imports for symbols per path.\n * Identical symbols from different paths are NOT handled, they should be checked before rendering.\n */\nexport function renderImports(imports: ImportDatum[]): string {\n // Aggregate symbols by import path, also deduplicating them\n const aggregatedImports = new Map<string, Set<string>>();\n for (const { symbol, path } of imports) {\n if (!aggregatedImports.has(path)) {\n aggregatedImports.set(path, new Set());\n }\n aggregatedImports.get(path)?.add(symbol);\n }\n // Render imports\n const renderedImports = [];\n for (const [path, symbols] of aggregatedImports) {\n const renderedSymbols = [...symbols].join(\", \");\n renderedImports.push(`import { ${renderedSymbols} } from \"${renderImportPath(path)}\";`);\n }\n return renderedImports.join(\"\\n\");\n}\n\ninterface RenderWithStoreCallbackData {\n /** `_store` variable prefixed with its type (undefined if library name) */\n _typedStore: string | undefined;\n /** `_store` variable (undefined if library name) */\n _store: string;\n /** Empty string if storeArgument is false, otherwise `\" (using the specified store)\"` */\n _commentSuffix: string;\n /** Prefix to differentiate different kinds of store usage within methods */\n _methodNamePrefix: string;\n /** Whether FieldLayout variable should be passed to store methods */\n _useExplicitFieldLayout?: boolean;\n}\n\n/**\n * Renders several versions of the callback's result, which access Store in different ways\n * @param storeArgument whether to render a version with `IStore _store` as an argument\n * @param callback renderer for a method which uses store\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithStore(\n storeArgument: boolean,\n callback: (data: RenderWithStoreCallbackData) => string,\n): string {\n let result = \"\";\n result += callback({ _typedStore: undefined, _store: \"StoreSwitch\", _commentSuffix: \"\", _methodNamePrefix: \"\" });\n result += callback({\n _typedStore: undefined,\n _store: \"StoreCore\",\n _commentSuffix: \"\",\n _methodNamePrefix: \"_\",\n _useExplicitFieldLayout: true,\n });\n\n if (storeArgument) {\n result +=\n \"\\n\" +\n callback({\n _typedStore: \"IStore _store\",\n _store: \"_store\",\n _commentSuffix: \" (using the specified store)\",\n _methodNamePrefix: \"\",\n });\n }\n\n return result;\n}\n\n/**\n * Renders several versions of the callback's result, which have different method name suffixes\n * @param withSuffixlessFieldMethods whether to render methods with an empty suffix\n * @param fieldName name of the field which the methods access, used for a suffix\n * @param callback renderer for a method to be suffixed\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithFieldSuffix(\n withSuffixlessFieldMethods: boolean,\n fieldName: string,\n callback: (_methodNameSuffix: string) => string,\n): string {\n const methodNameSuffix = `${fieldName[0].toUpperCase()}${fieldName.slice(1)}`;\n let result = \"\";\n result += callback(methodNameSuffix);\n\n if (withSuffixlessFieldMethods) {\n result += \"\\n\" + callback(\"\");\n }\n\n return result;\n}\n\n/**\n * Renders `_tableId` definition of the given table.\n * @param param0 static resource data needed to construct the table ID\n */\nexport function renderTableId({\n namespace,\n name,\n offchainOnly,\n}: Pick<StaticResourceData, \"namespace\" | \"name\" | \"offchainOnly\">): string {\n const tableId = resourceToHex({\n type: offchainOnly ? \"offchainTable\" : \"table\",\n namespace,\n name,\n });\n // turn table ID back into arguments that would be valid in `WorldResourceIdLib.encode` (like truncated names)\n const resource = hexToResource(tableId);\n return `\n // Hex below is the result of \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: ${offchainOnly ? \"RESOURCE_OFFCHAIN_TABLE\" : \"RESOURCE_TABLE\"} });\\`\n ResourceId constant _tableId = ResourceId.wrap(${tableId});\n `;\n}\n\n/**\n * Renders solidity typecasts to get from the given type to `bytes32`\n * @param name variable name to be typecasted\n * @param param1 type data\n */\nexport function renderValueTypeToBytes32(\n name: string,\n { typeUnwrap, internalTypeId }: Pick<RenderType, \"typeUnwrap\" | \"internalTypeId\">,\n): string {\n const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name;\n\n if (internalTypeId === \"bytes32\") {\n return innerText;\n } else if (/^bytes\\d{1,2}$/.test(internalTypeId)) {\n return `bytes32(${innerText})`;\n } else if (/^uint\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(${innerText}))`;\n } else if (/^int\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(int256(${innerText})))`;\n } else if (internalTypeId === \"address\") {\n return `bytes32(uint256(uint160(${innerText})))`;\n } else if (internalTypeId === \"bool\") {\n return `_boolToBytes32(${innerText})`;\n } else {\n throw new Error(`Unknown value type id ${internalTypeId}`);\n }\n}\n\n/**\n * Whether the storage representation of the given solidity type is left aligned\n */\nexport function isLeftAligned(field: Pick<RenderType, \"internalTypeId\">): boolean {\n return /^bytes\\d{1,2}$/.test(field.internalTypeId);\n}\n\n/**\n * The number of padding bits in the storage representation of a right-aligned solidity type\n */\nexport function getLeftPaddingBits(field: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">): number {\n if (isLeftAligned(field)) {\n return 0;\n } else {\n return 256 - field.staticByteLength * 8;\n }\n}\n\n/**\n * Internal helper to render `lineTerminator`-separated list of items mapped by `renderItem`\n */\nfunction internalRenderList<T>(\n lineTerminator: string,\n list: T[],\n renderItem: (item: T, index: number) => string,\n): string {\n return list\n .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? \"\" : lineTerminator))\n .join(\"\\n\");\n}\n","import { renderedSolidityHeader } from \"./common\";\n\n// importing this from config or store would be a cyclic dependency :(\ntype Enums = {\n readonly [name: string]: readonly [string, ...string[]];\n};\n\n/**\n * Render a list of enum data as solidity enum definitions\n */\nexport function renderEnums(enums: Enums): string {\n const enumDefinitions = Object.entries(enums).map(\n ([name, values]) => `\n enum ${name} {\n ${values.join(\", \")}\n }\n `,\n );\n\n return `\n ${renderedSolidityHeader}\n ${enumDefinitions.join(\"\")}\n `;\n}\n","import { RenderField, RenderKeyTuple, RenderType } from \"./types\";\n\n/**\n * Renders the necessary helper functions to typecast to/from the types of given fields and keys\n */\nexport function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: RenderKeyTuple[] }): string {\n const { fields, keyTuple } = options;\n\n let result = \"\";\n\n for (const wrappingHelper of getWrappingHelpers([...fields, ...keyTuple])) {\n result += wrappingHelper;\n }\n\n // bool is special - it's the only primitive value type that can't be typecasted to/from\n if (fields.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a value to a bool.\n * @dev Boolean values are encoded as uint8 (1 = true, 0 = false), but Solidity doesn't allow casting between uint8 and bool.\n * @param value The uint8 value to convert.\n * @return result The boolean value.\n */\n function _toBool(uint8 value) pure returns (bool result) {\n assembly {\n result := value\n }\n }\n `;\n }\n if (keyTuple.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a bool to a bytes32.\n * @dev The boolean value is casted to a bytes32 value with 0 or 1 at the least significant bit.\n */\n function _boolToBytes32(bool value) pure returns (bytes32 result) {\n assembly {\n result := value\n }\n }\n `;\n }\n\n return result;\n}\n\nfunction getWrappingHelpers(array: RenderType[]): string[] {\n const wrappers = new Map<string, string>();\n const unwrappers = new Map<string, string>();\n for (const { typeWrappingData, typeWrap, typeUnwrap, internalTypeId } of array) {\n if (!typeWrappingData) continue;\n const { kind } = typeWrappingData;\n\n if (kind === \"staticArray\") {\n const { elementType, staticLength } = typeWrappingData;\n wrappers.set(typeWrap, renderWrapperStaticArray(typeWrap, elementType, staticLength, internalTypeId));\n unwrappers.set(typeUnwrap, renderUnwrapperStaticArray(typeUnwrap, elementType, staticLength, internalTypeId));\n }\n }\n\n return [...wrappers.values(), ...unwrappers.values()];\n}\n\n/**\n * Renders a function to cast a dynamic array to a static array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderWrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // WARNING: ensure this still works if changing major solidity versions!\n // (the memory layout for static arrays may change)\n return `\n /**\n * @notice Cast a dynamic array to a static array.\n * @dev In memory static arrays are just dynamic arrays without the 32 length bytes,\n * so this function moves the pointer to the first element of the dynamic array.\n * If the length of the dynamic array is smaller than the static length,\n * the function returns an uninitialized array to avoid memory corruption.\n * @param _value The dynamic array to cast.\n * @return _result The static array.\n */\n function ${functionName}(\n ${internalTypeId} memory _value\n ) pure returns (\n ${elementType}[${staticLength}] memory _result\n ) {\n if (_value.length < ${staticLength}) {\n // return an uninitialized array if the length is smaller than the fixed length to avoid memory corruption\n return _result;\n } else {\n // in memory static arrays are just dynamic arrays without the 32 length bytes\n // (without the length check this could lead to memory corruption)\n assembly {\n _result := add(_value, 0x20)\n }\n }\n }\n `;\n}\n\n/**\n * Renders a function to cast a static array to a dynamic array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderUnwrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // byte length for memory copying (more efficient than a loop)\n const byteLength = staticLength * 32;\n // TODO to optimize memory usage consider generalizing TightEncoder to a render-time utility\n return `\n /**\n * @notice Copy a static array to a dynamic array.\n * @dev Static arrays don't have a length prefix, so this function copies the memory from the static array to a new dynamic array.\n * @param _value The static array to copy.\n * @return _result The dynamic array.\n */ \n function ${functionName}(\n ${elementType}[${staticLength}] memory _value\n ) pure returns (\n ${internalTypeId} memory _result\n ) {\n _result = new ${internalTypeId}(${staticLength});\n uint256 fromPointer;\n uint256 toPointer;\n assembly {\n fromPointer := _value\n toPointer := add(_result, 0x20)\n }\n Memory.copy(fromPointer, toPointer, ${byteLength});\n }\n `;\n}\n","import { SchemaType } from \"@latticexyz/schema-type/deprecated\";\n\nexport const schemaTypesToRecsTypeStrings: Record<SchemaType, string> = {\n [SchemaType.UINT8]: \"RecsType.Number\",\n [SchemaType.UINT16]: \"RecsType.Number\",\n [SchemaType.UINT24]: \"RecsType.Number\",\n [SchemaType.UINT32]: \"RecsType.Number\",\n [SchemaType.UINT40]: \"RecsType.Number\",\n [SchemaType.UINT48]: \"RecsType.Number\",\n [SchemaType.UINT56]: \"RecsType.BigInt\",\n [SchemaType.UINT64]: \"RecsType.BigInt\",\n [SchemaType.UINT72]: \"RecsType.BigInt\",\n [SchemaType.UINT80]: \"RecsType.BigInt\",\n [SchemaType.UINT88]: \"RecsType.BigInt\",\n [SchemaType.UINT96]: \"RecsType.BigInt\",\n [SchemaType.UINT104]: \"RecsType.BigInt\",\n [SchemaType.UINT112]: \"RecsType.BigInt\",\n [SchemaType.UINT120]: \"RecsType.BigInt\",\n [SchemaType.UINT128]: \"RecsType.BigInt\",\n [SchemaType.UINT136]: \"RecsType.BigInt\",\n [SchemaType.UINT144]: \"RecsType.BigInt\",\n [SchemaType.UINT152]: \"RecsType.BigInt\",\n [SchemaType.UINT160]: \"RecsType.BigInt\",\n [SchemaType.UINT168]: \"RecsType.BigInt\",\n [SchemaType.UINT176]: \"RecsType.BigInt\",\n [SchemaType.UINT184]: \"RecsType.BigInt\",\n [SchemaType.UINT192]: \"RecsType.BigInt\",\n [SchemaType.UINT200]: \"RecsType.BigInt\",\n [SchemaType.UINT208]: \"RecsType.BigInt\",\n [SchemaType.UINT216]: \"RecsType.BigInt\",\n [SchemaType.UINT224]: \"RecsType.BigInt\",\n [SchemaType.UINT232]: \"RecsType.BigInt\",\n [SchemaType.UINT240]: \"RecsType.BigInt\",\n [SchemaType.UINT248]: \"RecsType.BigInt\",\n [SchemaType.UINT256]: \"RecsType.BigInt\",\n [SchemaType.INT8]: \"RecsType.Number\",\n [SchemaType.INT16]: \"RecsType.Number\",\n [SchemaType.INT24]: \"RecsType.Number\",\n [SchemaType.INT32]: \"RecsType.Number\",\n [SchemaType.INT40]: \"RecsType.Number\",\n [SchemaType.INT48]: \"RecsType.Number\",\n [SchemaType.INT56]: \"RecsType.BigInt\",\n [SchemaType.INT64]: \"RecsType.BigInt\",\n [SchemaType.INT72]: \"RecsType.BigInt\",\n [SchemaType.INT80]: \"RecsType.BigInt\",\n [SchemaType.INT88]: \"RecsType.BigInt\",\n [SchemaType.INT96]: \"RecsType.BigInt\",\n [SchemaType.INT104]: \"RecsType.BigInt\",\n [SchemaType.INT112]: \"RecsType.BigInt\",\n [SchemaType.INT120]: \"RecsType.BigInt\",\n [SchemaType.INT128]: \"RecsType.BigInt\",\n [SchemaType.INT136]: \"RecsType.BigInt\",\n [SchemaType.INT144]: \"RecsType.BigInt\",\n [SchemaType.INT152]: \"RecsType.BigInt\",\n [SchemaType.INT160]: \"RecsType.BigInt\",\n [SchemaType.INT168]: \"RecsType.BigInt\",\n [SchemaType.INT176]: \"RecsType.BigInt\",\n [SchemaType.INT184]: \"RecsType.BigInt\",\n [SchemaType.INT192]: \"RecsType.BigInt\",\n [SchemaType.INT200]: \"RecsType.BigInt\",\n [SchemaType.INT208]: \"RecsType.BigInt\",\n [SchemaType.INT216]: \"RecsType.BigInt\",\n [SchemaType.INT224]: \"RecsType.BigInt\",\n [SchemaType.INT232]: \"RecsType.BigInt\",\n [SchemaType.INT240]: \"RecsType.BigInt\",\n [SchemaType.INT248]: \"RecsType.BigInt\",\n [SchemaType.INT256]: \"RecsType.BigInt\",\n [SchemaType.BYTES1]: \"RecsType.String\",\n [SchemaType.BYTES2]: \"RecsType.String\",\n [SchemaType.BYTES3]: \"RecsType.String\",\n [SchemaType.BYTES4]: \"RecsType.String\",\n [SchemaType.BYTES5]: \"RecsType.String\",\n [SchemaType.BYTES6]: \"RecsType.String\",\n [SchemaType.BYTES7]: \"RecsType.String\",\n [SchemaType.BYTES8]: \"RecsType.String\",\n [SchemaType.BYTES9]: \"RecsType.String\",\n [SchemaType.BYTES10]: \"RecsType.String\",\n [SchemaType.BYTES11]: \"RecsType.String\",\n [SchemaType.BYTES12]: \"RecsType.String\",\n [SchemaType.BYTES13]: \"RecsType.String\",\n [SchemaType.BYTES14]: \"RecsType.String\",\n [SchemaType.BYTES15]: \"RecsType.String\",\n [SchemaType.BYTES16]: \"RecsType.String\",\n [SchemaType.BYTES17]: \"RecsType.String\",\n [SchemaType.BYTES18]: \"RecsType.String\",\n [SchemaType.BYTES19]: \"RecsType.String\",\n [SchemaType.BYTES20]: \"RecsType.String\",\n [SchemaType.BYTES21]: \"RecsType.String\",\n [SchemaType.BYTES22]: \"RecsType.String\",\n [SchemaType.BYTES23]: \"RecsType.String\",\n [SchemaType.BYTES24]: \"RecsType.String\",\n [SchemaType.BYTES25]: \"RecsType.String\",\n [SchemaType.BYTES26]: \"RecsType.String\",\n [SchemaType.BYTES27]: \"RecsType.String\",\n [SchemaType.BYTES28]: \"RecsType.String\",\n [SchemaType.BYTES29]: \"RecsType.String\",\n [SchemaType.BYTES30]: \"RecsType.String\",\n [SchemaType.BYTES31]: \"RecsType.String\",\n [SchemaType.BYTES32]: \"RecsType.String\",\n [SchemaType.BOOL]: \"RecsType.Boolean\",\n [SchemaType.ADDRESS]: \"RecsType.String\",\n [SchemaType.UINT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES1_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES2_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES3_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES4_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES5_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES6_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES7_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES8_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES9_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES10_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES11_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES12_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES13_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES14_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES15_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES16_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES17_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES18_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES19_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES20_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES21_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES22_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES23_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES24_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES25_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES26_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES27_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES28_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES29_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES30_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES31_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES32_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BOOL_ARRAY]: \"RecsType.T\", // no boolean array\n [SchemaType.ADDRESS_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES]: \"RecsType.String\",\n [SchemaType.STRING]: \"RecsType.String\",\n};\n","import { parse, visit } from \"@solidity-parser/parser\";\nimport type {\n ContractDefinition,\n SourceUnit,\n TypeName,\n VariableDeclaration,\n} from \"@solidity-parser/parser/dist/src/ast-types\";\nimport { MUDError } from \"../../errors\";\n\nexport interface ContractInterfaceFunction {\n name: string;\n parameters: string[];\n stateMutability: string;\n returnParameters: string[];\n}\n\nexport interface ContractInterfaceError {\n name: string;\n parameters: string[];\n}\n\ninterface SymbolImport {\n symbol: string;\n path: string;\n}\n\n/**\n * Parse the contract data to get the functions necessary to generate an interface,\n * and symbols to import from the original contract.\n * @param source contents of a file with the solidity contract\n * @param contractName name of the contract\n * @returns interface data\n */\nexport function contractToInterface(\n source: string,\n contractName: string,\n): {\n functions: ContractInterfaceFunction[];\n errors: ContractInterfaceError[];\n symbolImports: SymbolImport[];\n} {\n const ast = parse(source);\n const contractNode = findContractNode(ast, contractName);\n let symbolImports: SymbolImport[] = [];\n const functions: ContractInterfaceFunction[] = [];\n const errors: ContractInterfaceError[] = [];\n\n if (!contractNode) {\n throw new MUDError(`Contract not found: ${contractName}`);\n }\n\n visit(contractNode, {\n FunctionDefinition({\n name,\n visibility,\n parameters,\n stateMutability,\n returnParameters,\n isConstructor,\n isFallback,\n isReceiveEther,\n }) {\n try {\n // skip constructor and fallbacks\n if (isConstructor || isFallback || isReceiveEther) return;\n // forbid default visibility (this check might be unnecessary, modern solidity already disallows this)\n if (visibility === \"default\") throw new MUDError(`Visibility is not specified`);\n\n if (visibility === \"external\" || visibility === \"public\") {\n functions.push({\n name: name === null ? \"\" : name,\n parameters: parameters.map(parseParameter),\n stateMutability: stateMutability || \"\",\n returnParameters: returnParameters === null ? [] : returnParameters.map(parseParameter),\n });\n\n for (const { typeName } of parameters.concat(returnParameters ?? [])) {\n const symbols = typeNameToSymbols(typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n }\n } catch (error: unknown) {\n if (error instanceof MUDError) {\n error.message = `Function \"${name}\" in contract \"${contractName}\": ${error.message}`;\n }\n throw error;\n }\n },\n CustomErrorDefinition({ name, parameters }) {\n errors.push({\n name,\n parameters: parameters.map(parseParameter),\n });\n\n for (const parameter of parameters) {\n const symbols = typeNameToSymbols(parameter.typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n },\n });\n\n return {\n functions,\n errors,\n symbolImports,\n };\n}\n\nexport function findContractNode(ast: SourceUnit, contractName: string): ContractDefinition | undefined {\n let contract: ContractDefinition | undefined = undefined;\n\n visit(ast, {\n ContractDefinition(node) {\n if (node.name === contractName) {\n contract = node;\n }\n },\n });\n\n return contract;\n}\n\nfunction parseParameter({ name, typeName, storageLocation }: VariableDeclaration): string {\n let typedNameWithLocation = \"\";\n\n const { name: flattenedTypeName, stateMutability } = flattenTypeName(typeName);\n // type name (e.g. uint256)\n typedNameWithLocation += flattenedTypeName;\n // optional mutability (e.g. address payable)\n if (stateMutability !== null) {\n typedNameWithLocation += ` ${stateMutability}`;\n }\n // location, when relevant (e.g. string memory)\n if (storageLocation !== null) {\n typedNameWithLocation += ` ${storageLocation}`;\n }\n // optional variable name\n if (name !== null) {\n typedNameWithLocation += ` ${name}`;\n }\n\n return typedNameWithLocation;\n}\n\nfunction flattenTypeName(typeName: TypeName | null): { name: string; stateMutability: string | null } {\n if (typeName === null) {\n return {\n name: \"\",\n stateMutability: null,\n };\n }\n if (typeName.type === \"ElementaryTypeName\") {\n return {\n name: typeName.name,\n stateMutability: typeName.stateMutability,\n };\n } else if (typeName.type === \"UserDefinedTypeName\") {\n return {\n name: typeName.namePath,\n stateMutability: null,\n };\n } else if (typeName.type === \"ArrayTypeName\") {\n let length = \"\";\n if (typeName.length?.type === \"NumberLiteral\") {\n length = typeName.length.number;\n } else if (typeName.length?.type === \"Identifier\") {\n length = typeName.length.name;\n }\n\n const { name, stateMutability } = flattenTypeName(typeName.baseTypeName);\n return {\n name: `${name}[${length}]`,\n stateMutability,\n };\n } else {\n // TODO function types are unsupported but could be useful\n throw new MUDError(`Invalid typeName.type ${typeName.type}`);\n }\n}\n\n// Get symbols that need to be imported for given typeName\nfunction typeNameToSymbols(typeName: TypeName | null): string[] {\n if (typeName?.type === \"UserDefinedTypeName\") {\n // split is needed to get a library, if types are internal to it\n const symbol = typeName.namePath.split(\".\")[0];\n return [symbol];\n } else if (typeName?.type === \"ArrayTypeName\") {\n const symbols = typeNameToSymbols(typeName.baseTypeName);\n // array types can also use symbols (constants) for length\n if (typeName.length?.type === \"Identifier\") {\n const innerTypeName = typeName.length.name;\n symbols.push(innerTypeName.split(\".\")[0]);\n }\n return symbols;\n } else {\n return [];\n }\n}\n\n// Get imports for given symbols.\n// To avoid circular dependencies of interfaces on their implementations,\n// symbols used for args/returns must always be imported from an auxiliary file.\n// To avoid parsing the entire project to build dependencies,\n// symbols must be imported with an explicit `import { symbol } from ...`\nfunction symbolsToImports(ast: SourceUnit, symbols: string[]): SymbolImport[] {\n const imports: SymbolImport[] = [];\n\n for (const symbol of symbols) {\n let symbolImport: SymbolImport | undefined;\n\n visit(ast, {\n ImportDirective({ path, symbolAliases }) {\n if (symbolAliases) {\n for (const symbolAndAlias of symbolAliases) {\n // either check the alias, or the original symbol if there's no alias\n const symbolAlias = symbolAndAlias[1] || symbolAndAlias[0];\n if (symbol === symbolAlias) {\n symbolImport = {\n // always use the original symbol for interface imports\n symbol: symbolAndAlias[0],\n path,\n };\n return;\n }\n }\n }\n },\n });\n\n if (symbolImport) {\n imports.push(symbolImport);\n } else {\n throw new MUDError(`Symbol \"${symbol}\" has no explicit import`);\n }\n }\n\n return imports;\n}\n","import prettier from \"prettier\";\nimport prettierPluginSolidity from \"prettier-plugin-solidity\";\n\n/**\n * Formats solidity code using prettier\n * @param content solidity code\n * @param prettierConfigPath optional path to a prettier config\n * @returns formatted solidity code\n */\nexport async function formatSolidity(content: string, prettierConfigPath?: string): Promise<string> {\n let config;\n if (prettierConfigPath) {\n config = await prettier.resolveConfig(prettierConfigPath);\n }\n try {\n return prettier.format(content, {\n plugins: [prettierPluginSolidity],\n parser: \"solidity-parse\",\n\n printWidth: 120,\n semi: true,\n tabWidth: 2,\n useTabs: false,\n bracketSpacing: true,\n\n ...config,\n });\n } catch (error) {\n let message;\n if (error instanceof Error) {\n message = error.message;\n } else {\n message = error;\n }\n console.log(`Error during output formatting: ${message}`);\n return content;\n }\n}\n\n/**\n * Formats typescript code using prettier\n * @param content typescript code\n * @returns formatted typescript code\n */\nexport async function formatTypescript(content: string): Promise<string> {\n return prettier.format(content, {\n parser: \"typescript\",\n });\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { formatSolidity, formatTypescript } from \"./format\";\nimport { debug } from \"../debug\";\n\n/**\n * Formats solidity code using prettier and write it to a file\n * @param output solidity code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteSolidity(output: string, fullOutputPath: string, logPrefix: string): Promise<void> {\n const formattedOutput = await formatSolidity(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n\n/**\n * Formats typescript code using prettier and write it to a file\n * @param output typescript code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteTypescript(\n output: string,\n fullOutputPath: string,\n logPrefix: string,\n): Promise<void> {\n const formattedOutput = await formatTypescript(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"codegen\");\nexport const error = parentDebug.extend(\"codegen\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n"],"mappings":";;;;;;;;;;;;;;;;AACA,SAAqC,eAAe,0BAA0B;;;ACD9E,OAAO,UAAU;AAIjB,SAAS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AAO,QAAQ;AACf,OAAOC,WAAU;;;ACCV,IAAMC,SAAQ,MAAY,OAAO,SAAS;AAC1C,IAAM,QAAQ,MAAY,OAAO,SAAS;AAGjDA,OAAM,MAAM,QAAQ,MAAM,KAAK,OAAO;AAGtC,MAAM,MAAM,QAAQ,MAAM,KAAK,OAAO;;;ADEtC,eAAsB,uBAAuB,QAAgB,gBAAwB,WAAkC;AACrH,QAAM,kBAAkB,MAAM,eAAe,MAAM;AAEnD,QAAM,GAAG,MAAMC,MAAK,QAAQ,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC;AAEhE,QAAM,GAAG,UAAU,gBAAgB,eAAe;AAClD,EAAAC,OAAM,GAAG,SAAS,KAAK,cAAc,EAAE;AACzC;AAQA,eAAsB,yBACpB,QACA,gBACA,WACe;AACf,QAAM,kBAAkB,MAAM,iBAAiB,MAAM;AAErD,QAAM,GAAG,MAAMD,MAAK,QAAQ,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC;AAEhE,QAAM,GAAG,UAAU,gBAAgB,eAAe;AAClD,EAAAC,OAAM,GAAG,SAAS,KAAK,cAAc,EAAE;AACzC;","names":["path","error","path","error","path","debug","path","debug"]}
|
|
1
|
+
{"version":3,"sources":["../src/codegen/render-solidity/abiToInterface.ts","../src/codegen/render-solidity/renderImportPath.ts","../src/codegen/render-solidity/common.ts","../src/codegen/render-solidity/renderEnums.ts","../src/codegen/render-solidity/renderTypeHelpers.ts","../src/codegen/render-typescript/schemaTypesToRecsTypeStrings.ts","../src/codegen/utils/contractToInterface.ts","../src/codegen/utils/findContractNode.ts","../src/codegen/utils/findSymbolImport.ts","../src/codegen/utils/format.ts","../src/codegen/utils/formatAndWrite.ts","../src/codegen/debug.ts","../src/codegen/utils/parseSystem.ts"],"sourcesContent":["import { AbiParameter, Hex } from \"viem\";\nimport { Abi, AbiError, AbiFunction, formatAbiItem, formatAbiParameter } from \"abitype\";\nimport { renderedSolidityHeader } from \"./common\";\nimport { hexToResource } from \"../../hexToResource\";\n\nfunction formatParam(param: AbiParameter): string {\n // return param.type === \"string\" || param.type === \"bytes\" || param.type === \"tuple\" || param.type.endsWith(\"]\")\n // ? `${formatAbiParameter(param)} memory`\n // : formatAbiParameter(param);\n return formatAbiParameter(param);\n}\n\nfunction formatFunction(item: AbiFunction): string {\n const params = item.inputs.map(formatParam).join(\", \");\n const returns = item.outputs.map(formatParam).join(\", \");\n return `function ${item.name}(${params}) external${returns.length ? ` returns (${returns})` : \"\"}`;\n}\n\nfunction formatSystemId(systemId: Hex): string {\n const resource = hexToResource(systemId);\n return `\n // equivalent to \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: RESOURCE_SYSTEM });\\`\n ResourceId constant systemId = ResourceId.wrap(${systemId});\n `;\n}\n\nexport type AbiToInterfaceOptions = {\n name: string;\n systemId?: Hex;\n abi: Abi;\n};\n\nexport function abiToInterface({ name, systemId, abi }: AbiToInterfaceOptions): string {\n const imports = systemId ? [`{ ResourceId } from \"@latticexyz/store/src/ResourceId.sol\"`] : [];\n const errors = abi.filter((item): item is AbiError => item.type === \"error\");\n const functions = abi.filter((item): item is AbiFunction => item.type === \"function\");\n\n return `\n ${renderedSolidityHeader}\n\n ${imports.map((item) => `import ${item};`).join(\"\\n\")}\n\n ${systemId ? formatSystemId(systemId) : \"\"}\n\n interface ${name} {\n ${errors.map((item) => `${formatAbiItem(item)};`).join(\"\\n\")}\n\n ${functions\n .map((item) => {\n if ([...item.inputs, ...item.outputs].some((param) => param.type.startsWith(\"tuple\"))) {\n return `// TODO: replace tuple with struct\\n// ${formatFunction(item)};`;\n }\n return `${formatFunction(item)};`;\n })\n .join(\"\\n\")}\n }\n `;\n}\n","import path from \"node:path\";\n\n// This will probably break for backslash-escaped POSIX paths,\n// but we'll worry about that later.\nfunction winToPosix(segment: string): string {\n return segment.replaceAll(path.win32.sep, path.posix.sep);\n}\n\nexport function renderImportPath(basePath: string, ...segments: readonly string[]): string {\n // Solidity compiler expects POSIX paths\n const fullPath = path.posix\n .join(winToPosix(basePath), ...segments.map(winToPosix))\n // remove trailing slash\n .replace(/\\/$/, \"\");\n\n // `path.join` strips the leading `./`\n // so if we started with a relative path, make it relative again\n if (basePath.startsWith(\".\")) {\n const relativePath = \"./\" + fullPath;\n return relativePath.replace(/^(\\.\\/)+\\./, \".\");\n }\n\n return fullPath;\n}\n","import { ImportDatum, StaticResourceData, RenderKeyTuple, RenderType } from \"./types\";\nimport { resourceToHex } from \"../../resourceToHex\";\nimport { hexToResource } from \"../../hexToResource\";\nimport { renderImportPath } from \"./renderImportPath\";\nimport { isDefined } from \"../../utils\";\n\n/**\n * Common header for all codegenerated solidity files\n */\nexport const renderedSolidityHeader = `// SPDX-License-Identifier: MIT\npragma solidity >=0.8.24;\n\n/* Autogenerated file. Do not edit manually. */`;\n\n/**\n * Renders a list of lines\n */\nexport function renderList<T>(list: T[], renderItem: (item: T, index: number) => string): string {\n return internalRenderList(\"\", list, renderItem);\n}\n\n/**\n * Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones\n */\nexport function renderArguments(args: (string | undefined)[]): string {\n return args\n .filter(isDefined)\n .filter((arg) => arg !== \"\")\n .join(\", \");\n}\n\ninterface RenderedCommonData {\n /** `_tableId` variable prefixed with its type (empty string if absent) */\n _typedTableId: string;\n /** Comma-separated table key names prefixed with their types (empty string if 0 keys) */\n _typedKeyArgs: string;\n /** Definition and initialization of the dynamic `_keyTuple` bytes32 array */\n _keyTupleDefinition: string;\n}\n\n/**\n * Renders some solidity statements commonly used within table libraries\n * @param param0.staticResourceData static data about the table library\n * @param param0.keyTuple key tuple of the table library\n * @returns Rendered statement strings\n */\nexport function renderCommonData({\n staticResourceData,\n keyTuple,\n}: {\n staticResourceData?: StaticResourceData;\n keyTuple: RenderKeyTuple[];\n}): RenderedCommonData {\n // static resource means static tableId as well, and no tableId arguments\n const _typedTableId = staticResourceData ? \"\" : \"ResourceId _tableId\";\n const _typedKeyArgs = renderArguments(keyTuple.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n\n const _keyTupleDefinition = `\n bytes32[] memory _keyTuple = new bytes32[](${keyTuple.length});\n ${renderList(keyTuple, (key, index) => `_keyTuple[${index}] = ${renderValueTypeToBytes32(key.name, key)};`)}\n `;\n\n return {\n _typedTableId,\n _typedKeyArgs,\n _keyTupleDefinition,\n };\n}\n\n/**\n * Aggregates, deduplicates and renders imports for symbols per path.\n * Identical symbols from different paths are NOT handled, they should be checked before rendering.\n */\nexport function renderImports(imports: ImportDatum[]): string {\n // Aggregate symbols by import path, also deduplicating them\n const aggregatedImports = new Map<string, Set<string>>();\n for (const { symbol, path } of imports) {\n if (!aggregatedImports.has(path)) {\n aggregatedImports.set(path, new Set());\n }\n aggregatedImports.get(path)?.add(symbol);\n }\n // Render imports\n const renderedImports = [];\n for (const [path, symbols] of aggregatedImports) {\n const renderedSymbols = [...symbols].join(\", \");\n renderedImports.push(`import { ${renderedSymbols} } from \"${renderImportPath(path)}\";`);\n }\n return renderedImports.join(\"\\n\");\n}\n\ninterface RenderWithStoreCallbackData {\n /** `_store` variable prefixed with its type (undefined if library name) */\n _typedStore: string | undefined;\n /** `_store` variable (undefined if library name) */\n _store: string;\n /** Empty string if storeArgument is false, otherwise `\" (using the specified store)\"` */\n _commentSuffix: string;\n /** Prefix to differentiate different kinds of store usage within methods */\n _methodNamePrefix: string;\n /** Whether FieldLayout variable should be passed to store methods */\n _useExplicitFieldLayout?: boolean;\n}\n\n/**\n * Renders several versions of the callback's result, which access Store in different ways\n * @param storeArgument whether to render a version with `IStore _store` as an argument\n * @param callback renderer for a method which uses store\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithStore(\n storeArgument: boolean,\n callback: (data: RenderWithStoreCallbackData) => string,\n): string {\n let result = \"\";\n result += callback({ _typedStore: undefined, _store: \"StoreSwitch\", _commentSuffix: \"\", _methodNamePrefix: \"\" });\n result += callback({\n _typedStore: undefined,\n _store: \"StoreCore\",\n _commentSuffix: \"\",\n _methodNamePrefix: \"_\",\n _useExplicitFieldLayout: true,\n });\n\n if (storeArgument) {\n result +=\n \"\\n\" +\n callback({\n _typedStore: \"IStore _store\",\n _store: \"_store\",\n _commentSuffix: \" (using the specified store)\",\n _methodNamePrefix: \"\",\n });\n }\n\n return result;\n}\n\n/**\n * Renders several versions of the callback's result, which have different method name suffixes\n * @param withSuffixlessFieldMethods whether to render methods with an empty suffix\n * @param fieldName name of the field which the methods access, used for a suffix\n * @param callback renderer for a method to be suffixed\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithFieldSuffix(\n withSuffixlessFieldMethods: boolean,\n fieldName: string,\n callback: (_methodNameSuffix: string) => string,\n): string {\n const methodNameSuffix = `${fieldName[0].toUpperCase()}${fieldName.slice(1)}`;\n let result = \"\";\n result += callback(methodNameSuffix);\n\n if (withSuffixlessFieldMethods) {\n result += \"\\n\" + callback(\"\");\n }\n\n return result;\n}\n\n/**\n * Renders `_tableId` definition of the given table.\n * @param param0 static resource data needed to construct the table ID\n */\nexport function renderTableId({\n namespace,\n name,\n offchainOnly,\n}: Pick<StaticResourceData, \"namespace\" | \"name\" | \"offchainOnly\">): string {\n const tableId = resourceToHex({\n type: offchainOnly ? \"offchainTable\" : \"table\",\n namespace,\n name,\n });\n // turn table ID back into arguments that would be valid in `WorldResourceIdLib.encode` (like truncated names)\n const resource = hexToResource(tableId);\n return `\n // Hex below is the result of \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: ${offchainOnly ? \"RESOURCE_OFFCHAIN_TABLE\" : \"RESOURCE_TABLE\"} });\\`\n ResourceId constant _tableId = ResourceId.wrap(${tableId});\n `;\n}\n\n/**\n * Renders solidity typecasts to get from the given type to `bytes32`\n * @param name variable name to be typecasted\n * @param param1 type data\n */\nexport function renderValueTypeToBytes32(\n name: string,\n { typeUnwrap, internalTypeId }: Pick<RenderType, \"typeUnwrap\" | \"internalTypeId\">,\n): string {\n const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name;\n\n if (internalTypeId === \"bytes32\") {\n return innerText;\n } else if (/^bytes\\d{1,2}$/.test(internalTypeId)) {\n return `bytes32(${innerText})`;\n } else if (/^uint\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(${innerText}))`;\n } else if (/^int\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(int256(${innerText})))`;\n } else if (internalTypeId === \"address\") {\n return `bytes32(uint256(uint160(${innerText})))`;\n } else if (internalTypeId === \"bool\") {\n return `_boolToBytes32(${innerText})`;\n } else {\n throw new Error(`Unknown value type id ${internalTypeId}`);\n }\n}\n\n/**\n * Whether the storage representation of the given solidity type is left aligned\n */\nexport function isLeftAligned(field: Pick<RenderType, \"internalTypeId\">): boolean {\n return /^bytes\\d{1,2}$/.test(field.internalTypeId);\n}\n\n/**\n * The number of padding bits in the storage representation of a right-aligned solidity type\n */\nexport function getLeftPaddingBits(field: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">): number {\n if (isLeftAligned(field)) {\n return 0;\n } else {\n return 256 - field.staticByteLength * 8;\n }\n}\n\n/**\n * Internal helper to render `lineTerminator`-separated list of items mapped by `renderItem`\n */\nfunction internalRenderList<T>(\n lineTerminator: string,\n list: T[],\n renderItem: (item: T, index: number) => string,\n): string {\n return list\n .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? \"\" : lineTerminator))\n .join(\"\\n\");\n}\n","import { renderedSolidityHeader } from \"./common\";\n\n// importing this from config or store would be a cyclic dependency :(\ntype Enums = {\n readonly [name: string]: readonly [string, ...string[]];\n};\n\n/**\n * Render a list of enum data as solidity enum definitions\n */\nexport function renderEnums(enums: Enums): string {\n const enumDefinitions = Object.entries(enums).map(\n ([name, values]) => `\n enum ${name} {\n ${values.join(\", \")}\n }\n `,\n );\n\n return `\n ${renderedSolidityHeader}\n ${enumDefinitions.join(\"\")}\n `;\n}\n","import { RenderField, RenderKeyTuple, RenderType } from \"./types\";\n\n/**\n * Renders the necessary helper functions to typecast to/from the types of given fields and keys\n */\nexport function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: RenderKeyTuple[] }): string {\n const { fields, keyTuple } = options;\n\n let result = \"\";\n\n for (const wrappingHelper of getWrappingHelpers([...fields, ...keyTuple])) {\n result += wrappingHelper;\n }\n\n // bool is special - it's the only primitive value type that can't be typecasted to/from\n if (fields.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a value to a bool.\n * @dev Boolean values are encoded as uint8 (1 = true, 0 = false), but Solidity doesn't allow casting between uint8 and bool.\n * @param value The uint8 value to convert.\n * @return result The boolean value.\n */\n function _toBool(uint8 value) pure returns (bool result) {\n assembly {\n result := value\n }\n }\n `;\n }\n if (keyTuple.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a bool to a bytes32.\n * @dev The boolean value is casted to a bytes32 value with 0 or 1 at the least significant bit.\n */\n function _boolToBytes32(bool value) pure returns (bytes32 result) {\n assembly {\n result := value\n }\n }\n `;\n }\n\n return result;\n}\n\nfunction getWrappingHelpers(array: RenderType[]): string[] {\n const wrappers = new Map<string, string>();\n const unwrappers = new Map<string, string>();\n for (const { typeWrappingData, typeWrap, typeUnwrap, internalTypeId } of array) {\n if (!typeWrappingData) continue;\n const { kind } = typeWrappingData;\n\n if (kind === \"staticArray\") {\n const { elementType, staticLength } = typeWrappingData;\n wrappers.set(typeWrap, renderWrapperStaticArray(typeWrap, elementType, staticLength, internalTypeId));\n unwrappers.set(typeUnwrap, renderUnwrapperStaticArray(typeUnwrap, elementType, staticLength, internalTypeId));\n }\n }\n\n return [...wrappers.values(), ...unwrappers.values()];\n}\n\n/**\n * Renders a function to cast a dynamic array to a static array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderWrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // WARNING: ensure this still works if changing major solidity versions!\n // (the memory layout for static arrays may change)\n return `\n /**\n * @notice Cast a dynamic array to a static array.\n * @dev In memory static arrays are just dynamic arrays without the 32 length bytes,\n * so this function moves the pointer to the first element of the dynamic array.\n * If the length of the dynamic array is smaller than the static length,\n * the function returns an uninitialized array to avoid memory corruption.\n * @param _value The dynamic array to cast.\n * @return _result The static array.\n */\n function ${functionName}(\n ${internalTypeId} memory _value\n ) pure returns (\n ${elementType}[${staticLength}] memory _result\n ) {\n if (_value.length < ${staticLength}) {\n // return an uninitialized array if the length is smaller than the fixed length to avoid memory corruption\n return _result;\n } else {\n // in memory static arrays are just dynamic arrays without the 32 length bytes\n // (without the length check this could lead to memory corruption)\n assembly {\n _result := add(_value, 0x20)\n }\n }\n }\n `;\n}\n\n/**\n * Renders a function to cast a static array to a dynamic array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderUnwrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // byte length for memory copying (more efficient than a loop)\n const byteLength = staticLength * 32;\n // TODO to optimize memory usage consider generalizing TightEncoder to a render-time utility\n return `\n /**\n * @notice Copy a static array to a dynamic array.\n * @dev Static arrays don't have a length prefix, so this function copies the memory from the static array to a new dynamic array.\n * @param _value The static array to copy.\n * @return _result The dynamic array.\n */ \n function ${functionName}(\n ${elementType}[${staticLength}] memory _value\n ) pure returns (\n ${internalTypeId} memory _result\n ) {\n _result = new ${internalTypeId}(${staticLength});\n uint256 fromPointer;\n uint256 toPointer;\n assembly {\n fromPointer := _value\n toPointer := add(_result, 0x20)\n }\n Memory.copy(fromPointer, toPointer, ${byteLength});\n }\n `;\n}\n","import { SchemaType } from \"@latticexyz/schema-type/deprecated\";\n\nexport const schemaTypesToRecsTypeStrings: Record<SchemaType, string> = {\n [SchemaType.UINT8]: \"RecsType.Number\",\n [SchemaType.UINT16]: \"RecsType.Number\",\n [SchemaType.UINT24]: \"RecsType.Number\",\n [SchemaType.UINT32]: \"RecsType.Number\",\n [SchemaType.UINT40]: \"RecsType.Number\",\n [SchemaType.UINT48]: \"RecsType.Number\",\n [SchemaType.UINT56]: \"RecsType.BigInt\",\n [SchemaType.UINT64]: \"RecsType.BigInt\",\n [SchemaType.UINT72]: \"RecsType.BigInt\",\n [SchemaType.UINT80]: \"RecsType.BigInt\",\n [SchemaType.UINT88]: \"RecsType.BigInt\",\n [SchemaType.UINT96]: \"RecsType.BigInt\",\n [SchemaType.UINT104]: \"RecsType.BigInt\",\n [SchemaType.UINT112]: \"RecsType.BigInt\",\n [SchemaType.UINT120]: \"RecsType.BigInt\",\n [SchemaType.UINT128]: \"RecsType.BigInt\",\n [SchemaType.UINT136]: \"RecsType.BigInt\",\n [SchemaType.UINT144]: \"RecsType.BigInt\",\n [SchemaType.UINT152]: \"RecsType.BigInt\",\n [SchemaType.UINT160]: \"RecsType.BigInt\",\n [SchemaType.UINT168]: \"RecsType.BigInt\",\n [SchemaType.UINT176]: \"RecsType.BigInt\",\n [SchemaType.UINT184]: \"RecsType.BigInt\",\n [SchemaType.UINT192]: \"RecsType.BigInt\",\n [SchemaType.UINT200]: \"RecsType.BigInt\",\n [SchemaType.UINT208]: \"RecsType.BigInt\",\n [SchemaType.UINT216]: \"RecsType.BigInt\",\n [SchemaType.UINT224]: \"RecsType.BigInt\",\n [SchemaType.UINT232]: \"RecsType.BigInt\",\n [SchemaType.UINT240]: \"RecsType.BigInt\",\n [SchemaType.UINT248]: \"RecsType.BigInt\",\n [SchemaType.UINT256]: \"RecsType.BigInt\",\n [SchemaType.INT8]: \"RecsType.Number\",\n [SchemaType.INT16]: \"RecsType.Number\",\n [SchemaType.INT24]: \"RecsType.Number\",\n [SchemaType.INT32]: \"RecsType.Number\",\n [SchemaType.INT40]: \"RecsType.Number\",\n [SchemaType.INT48]: \"RecsType.Number\",\n [SchemaType.INT56]: \"RecsType.BigInt\",\n [SchemaType.INT64]: \"RecsType.BigInt\",\n [SchemaType.INT72]: \"RecsType.BigInt\",\n [SchemaType.INT80]: \"RecsType.BigInt\",\n [SchemaType.INT88]: \"RecsType.BigInt\",\n [SchemaType.INT96]: \"RecsType.BigInt\",\n [SchemaType.INT104]: \"RecsType.BigInt\",\n [SchemaType.INT112]: \"RecsType.BigInt\",\n [SchemaType.INT120]: \"RecsType.BigInt\",\n [SchemaType.INT128]: \"RecsType.BigInt\",\n [SchemaType.INT136]: \"RecsType.BigInt\",\n [SchemaType.INT144]: \"RecsType.BigInt\",\n [SchemaType.INT152]: \"RecsType.BigInt\",\n [SchemaType.INT160]: \"RecsType.BigInt\",\n [SchemaType.INT168]: \"RecsType.BigInt\",\n [SchemaType.INT176]: \"RecsType.BigInt\",\n [SchemaType.INT184]: \"RecsType.BigInt\",\n [SchemaType.INT192]: \"RecsType.BigInt\",\n [SchemaType.INT200]: \"RecsType.BigInt\",\n [SchemaType.INT208]: \"RecsType.BigInt\",\n [SchemaType.INT216]: \"RecsType.BigInt\",\n [SchemaType.INT224]: \"RecsType.BigInt\",\n [SchemaType.INT232]: \"RecsType.BigInt\",\n [SchemaType.INT240]: \"RecsType.BigInt\",\n [SchemaType.INT248]: \"RecsType.BigInt\",\n [SchemaType.INT256]: \"RecsType.BigInt\",\n [SchemaType.BYTES1]: \"RecsType.String\",\n [SchemaType.BYTES2]: \"RecsType.String\",\n [SchemaType.BYTES3]: \"RecsType.String\",\n [SchemaType.BYTES4]: \"RecsType.String\",\n [SchemaType.BYTES5]: \"RecsType.String\",\n [SchemaType.BYTES6]: \"RecsType.String\",\n [SchemaType.BYTES7]: \"RecsType.String\",\n [SchemaType.BYTES8]: \"RecsType.String\",\n [SchemaType.BYTES9]: \"RecsType.String\",\n [SchemaType.BYTES10]: \"RecsType.String\",\n [SchemaType.BYTES11]: \"RecsType.String\",\n [SchemaType.BYTES12]: \"RecsType.String\",\n [SchemaType.BYTES13]: \"RecsType.String\",\n [SchemaType.BYTES14]: \"RecsType.String\",\n [SchemaType.BYTES15]: \"RecsType.String\",\n [SchemaType.BYTES16]: \"RecsType.String\",\n [SchemaType.BYTES17]: \"RecsType.String\",\n [SchemaType.BYTES18]: \"RecsType.String\",\n [SchemaType.BYTES19]: \"RecsType.String\",\n [SchemaType.BYTES20]: \"RecsType.String\",\n [SchemaType.BYTES21]: \"RecsType.String\",\n [SchemaType.BYTES22]: \"RecsType.String\",\n [SchemaType.BYTES23]: \"RecsType.String\",\n [SchemaType.BYTES24]: \"RecsType.String\",\n [SchemaType.BYTES25]: \"RecsType.String\",\n [SchemaType.BYTES26]: \"RecsType.String\",\n [SchemaType.BYTES27]: \"RecsType.String\",\n [SchemaType.BYTES28]: \"RecsType.String\",\n [SchemaType.BYTES29]: \"RecsType.String\",\n [SchemaType.BYTES30]: \"RecsType.String\",\n [SchemaType.BYTES31]: \"RecsType.String\",\n [SchemaType.BYTES32]: \"RecsType.String\",\n [SchemaType.BOOL]: \"RecsType.Boolean\",\n [SchemaType.ADDRESS]: \"RecsType.String\",\n [SchemaType.UINT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES1_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES2_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES3_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES4_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES5_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES6_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES7_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES8_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES9_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES10_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES11_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES12_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES13_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES14_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES15_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES16_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES17_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES18_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES19_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES20_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES21_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES22_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES23_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES24_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES25_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES26_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES27_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES28_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES29_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES30_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES31_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES32_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BOOL_ARRAY]: \"RecsType.T\", // no boolean array\n [SchemaType.ADDRESS_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES]: \"RecsType.String\",\n [SchemaType.STRING]: \"RecsType.String\",\n};\n","import { parse, visit } from \"@solidity-parser/parser\";\nimport type { SourceUnit, TypeName, VariableDeclaration } from \"@solidity-parser/parser/dist/src/ast-types\";\nimport { MUDError } from \"../../errors\";\nimport { findContractNode } from \"./findContractNode\";\nimport { SymbolImport, findSymbolImport } from \"./findSymbolImport\";\n\nexport interface ContractInterfaceFunction {\n name: string;\n parameters: string[];\n stateMutability: string;\n returnParameters: string[];\n}\n\nexport interface ContractInterfaceError {\n name: string;\n parameters: string[];\n}\n\n/**\n * Parse the contract data to get the functions necessary to generate an interface,\n * and symbols to import from the original contract.\n * @param source contents of a file with the solidity contract\n * @param contractName name of the contract\n * @returns interface data\n */\nexport function contractToInterface(\n source: string,\n contractName: string,\n): {\n functions: ContractInterfaceFunction[];\n errors: ContractInterfaceError[];\n symbolImports: SymbolImport[];\n} {\n const ast = parse(source);\n const contractNode = findContractNode(ast, contractName);\n let symbolImports: SymbolImport[] = [];\n const functions: ContractInterfaceFunction[] = [];\n const errors: ContractInterfaceError[] = [];\n\n if (!contractNode) {\n throw new MUDError(`Contract not found: ${contractName}`);\n }\n\n visit(contractNode, {\n FunctionDefinition({\n name,\n visibility,\n parameters,\n stateMutability,\n returnParameters,\n isConstructor,\n isFallback,\n isReceiveEther,\n }) {\n try {\n // skip constructor and fallbacks\n if (isConstructor || isFallback || isReceiveEther) return;\n // forbid default visibility (this check might be unnecessary, modern solidity already disallows this)\n if (visibility === \"default\") throw new MUDError(`Visibility is not specified`);\n\n if (visibility === \"external\" || visibility === \"public\") {\n functions.push({\n name: name === null ? \"\" : name,\n parameters: parameters.map(parseParameter),\n stateMutability: stateMutability || \"\",\n returnParameters: returnParameters === null ? [] : returnParameters.map(parseParameter),\n });\n\n for (const { typeName } of parameters.concat(returnParameters ?? [])) {\n const symbols = typeNameToSymbols(typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n }\n } catch (error: unknown) {\n if (error instanceof MUDError) {\n error.message = `Function \"${name}\" in contract \"${contractName}\": ${error.message}`;\n }\n throw error;\n }\n },\n CustomErrorDefinition({ name, parameters }) {\n errors.push({\n name,\n parameters: parameters.map(parseParameter),\n });\n\n for (const parameter of parameters) {\n const symbols = typeNameToSymbols(parameter.typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n },\n });\n\n return {\n functions,\n errors,\n symbolImports,\n };\n}\n\nfunction parseParameter({ name, typeName, storageLocation }: VariableDeclaration): string {\n let typedNameWithLocation = \"\";\n\n const { name: flattenedTypeName, stateMutability } = flattenTypeName(typeName);\n // type name (e.g. uint256)\n typedNameWithLocation += flattenedTypeName;\n // optional mutability (e.g. address payable)\n if (stateMutability !== null) {\n typedNameWithLocation += ` ${stateMutability}`;\n }\n // location, when relevant (e.g. string memory)\n if (storageLocation !== null) {\n typedNameWithLocation += ` ${storageLocation}`;\n }\n // optional variable name\n if (name !== null) {\n typedNameWithLocation += ` ${name}`;\n }\n\n return typedNameWithLocation;\n}\n\nfunction flattenTypeName(typeName: TypeName | null): { name: string; stateMutability: string | null } {\n if (typeName === null) {\n return {\n name: \"\",\n stateMutability: null,\n };\n }\n if (typeName.type === \"ElementaryTypeName\") {\n return {\n name: typeName.name,\n stateMutability: typeName.stateMutability,\n };\n } else if (typeName.type === \"UserDefinedTypeName\") {\n return {\n name: typeName.namePath,\n stateMutability: null,\n };\n } else if (typeName.type === \"ArrayTypeName\") {\n let length = \"\";\n if (typeName.length?.type === \"NumberLiteral\") {\n length = typeName.length.number;\n } else if (typeName.length?.type === \"Identifier\") {\n length = typeName.length.name;\n }\n\n const { name, stateMutability } = flattenTypeName(typeName.baseTypeName);\n return {\n name: `${name}[${length}]`,\n stateMutability,\n };\n } else {\n // TODO function types are unsupported but could be useful\n throw new MUDError(`Invalid typeName.type ${typeName.type}`);\n }\n}\n\n// Get symbols that need to be imported for given typeName\nfunction typeNameToSymbols(typeName: TypeName | null): string[] {\n if (typeName?.type === \"UserDefinedTypeName\") {\n // split is needed to get a library, if types are internal to it\n const symbol = typeName.namePath.split(\".\")[0];\n return [symbol];\n } else if (typeName?.type === \"ArrayTypeName\") {\n const symbols = typeNameToSymbols(typeName.baseTypeName);\n // array types can also use symbols (constants) for length\n if (typeName.length?.type === \"Identifier\") {\n const innerTypeName = typeName.length.name;\n symbols.push(innerTypeName.split(\".\")[0]);\n }\n return symbols;\n } else {\n return [];\n }\n}\n\nfunction symbolsToImports(ast: SourceUnit, symbols: string[]): SymbolImport[] {\n return symbols.map((symbol) => {\n const symbolImport = findSymbolImport(ast, symbol);\n if (!symbolImport) throw new MUDError(`Symbol \"${symbol}\" has no explicit import`);\n return symbolImport;\n });\n}\n","import { visit } from \"@solidity-parser/parser\";\nimport type { ContractDefinition, SourceUnit } from \"@solidity-parser/parser/dist/src/ast-types\";\n\nexport function findContractNode(ast: SourceUnit, contractName: string): ContractDefinition | undefined {\n let contract: ContractDefinition | undefined = undefined;\n\n visit(ast, {\n ContractDefinition(node) {\n if (node.name === contractName) {\n contract = node;\n }\n },\n });\n\n return contract;\n}\n","import { visit } from \"@solidity-parser/parser\";\nimport type { SourceUnit } from \"@solidity-parser/parser/dist/src/ast-types\";\n\nexport interface SymbolImport {\n symbol: string;\n path: string;\n}\n\n/**\n * Get import for given symbol.\n *\n * To avoid circular dependencies of interfaces on their implementations,\n * symbols used for args/returns must always be imported from an auxiliary file.\n * To avoid parsing the entire project to build dependencies,\n * symbols must be imported with an explicit `import { symbol } from ...`\n */\nexport function findSymbolImport(ast: SourceUnit, symbol: string): SymbolImport | undefined {\n let symbolImport: SymbolImport | undefined;\n\n visit(ast, {\n ImportDirective({ path, symbolAliases }) {\n if (symbolAliases) {\n for (const symbolAndAlias of symbolAliases) {\n // either check the alias, or the original symbol if there's no alias\n const symbolAlias = symbolAndAlias[1] ?? symbolAndAlias[0];\n if (symbol === symbolAlias) {\n symbolImport = {\n // always use the original symbol for interface imports\n symbol: symbolAndAlias[0],\n path,\n };\n return;\n }\n }\n }\n },\n });\n\n return symbolImport;\n}\n","import prettier from \"prettier\";\nimport prettierPluginSolidity from \"prettier-plugin-solidity\";\n\n/**\n * Formats solidity code using prettier\n * @param content solidity code\n * @param prettierConfigPath optional path to a prettier config\n * @returns formatted solidity code\n */\nexport async function formatSolidity(content: string, prettierConfigPath?: string): Promise<string> {\n let config;\n if (prettierConfigPath) {\n config = await prettier.resolveConfig(prettierConfigPath);\n }\n try {\n return prettier.format(content, {\n plugins: [prettierPluginSolidity],\n parser: \"solidity-parse\",\n\n printWidth: 120,\n semi: true,\n tabWidth: 2,\n useTabs: false,\n bracketSpacing: true,\n\n ...config,\n });\n } catch (error) {\n let message;\n if (error instanceof Error) {\n message = error.message;\n } else {\n message = error;\n }\n console.log(`Error during output formatting: ${message}`);\n return content;\n }\n}\n\n/**\n * Formats typescript code using prettier\n * @param content typescript code\n * @returns formatted typescript code\n */\nexport async function formatTypescript(content: string): Promise<string> {\n return prettier.format(content, {\n parser: \"typescript\",\n });\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { formatSolidity, formatTypescript } from \"./format\";\nimport { debug, error } from \"../debug\";\n\n/**\n * Formats solidity code using prettier and write it to a file\n * @param content solidity code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteSolidity(\n content: string,\n fullOutputPath: string,\n logPrefix: string,\n): Promise<void> {\n let output = content;\n try {\n output = await formatSolidity(output);\n } catch (e) {\n error(`Error while attempting to format ${fullOutputPath}`, e);\n }\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n await fs.writeFile(fullOutputPath, output);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n\n/**\n * Formats typescript code using prettier and write it to a file\n * @param output typescript code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteTypescript(\n output: string,\n fullOutputPath: string,\n logPrefix: string,\n): Promise<void> {\n const formattedOutput = await formatTypescript(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"codegen\");\nexport const error = parentDebug.extend(\"codegen\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { parse, visit } from \"@solidity-parser/parser\";\n\nimport { findContractNode } from \"./findContractNode\";\nimport { findSymbolImport } from \"./findSymbolImport\";\n\nconst baseSystemName = \"System\";\nconst baseSystemPath = \"@latticexyz/world/src/System.sol\";\n\nexport function parseSystem(\n source: string,\n contractName: string,\n): undefined | { contractType: \"contract\" | \"abstract\" } {\n const ast = parse(source);\n const contractNode = findContractNode(ast, contractName);\n if (!contractNode) return;\n\n const contractType = contractNode.kind;\n // skip libraries and interfaces\n // we allow abstract systems here so that we can create system libraries from them but without deploying them\n if (contractType !== \"contract\" && contractType !== \"abstract\") return;\n\n const isSystem = ((): boolean => {\n // if using the System suffix, assume its a system\n if (contractName.endsWith(\"System\") && contractName !== baseSystemName) return true;\n\n // otherwise check if we're inheriting from the base system\n let extendsBaseSystem = false;\n visit(contractNode, {\n InheritanceSpecifier(node) {\n if (node.baseName.namePath === baseSystemName) {\n extendsBaseSystem = true;\n }\n },\n });\n return extendsBaseSystem && findSymbolImport(ast, baseSystemName)?.path === baseSystemPath;\n })();\n\n if (isSystem) {\n return { contractType };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AACA,SAAqC,eAAe,0BAA0B;;;ACD9E,OAAO,UAAU;AAIjB,SAAS,WAAW,SAAyB;AAC3C,SAAO,QAAQ,WAAW,KAAK,MAAM,KAAK,KAAK,MAAM,GAAG;AAC1D;AAEO,SAAS,iBAAiB,aAAqB,UAAqC;AAEzF,QAAM,WAAW,KAAK,MACnB,KAAK,WAAW,QAAQ,GAAG,GAAG,SAAS,IAAI,UAAU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AiB,KAAK,cAAc,GAAG,SAAS;AAAA,EAC9E,GAAG;AAEH,MAAI,UAAU;AACZ,WAAO,EAAE,aAAa;AAAA,EACxB;AACF;","names":["path","visit","visit","path","visit","error","error","path","debug","path","debug","parse","visit","parse","visit"]}
|
package/dist/internal.d.ts
CHANGED
|
@@ -33,4 +33,11 @@ declare function getContractAddress({ deployerAddress, bytecode, salt, }: {
|
|
|
33
33
|
|
|
34
34
|
declare function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined>;
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
type WiresawOptions<transport extends Transport> = {
|
|
37
|
+
wiresaw: transport;
|
|
38
|
+
fallbackBundler?: Transport;
|
|
39
|
+
fallbackEth?: Transport;
|
|
40
|
+
};
|
|
41
|
+
declare function wiresaw<const wiresawTransport extends Transport>(transport: WiresawOptions<wiresawTransport>): wiresawTransport;
|
|
42
|
+
|
|
43
|
+
export { type Contract, ensureContract, ensureContractsDeployed, ensureDeployer, getContractAddress, getDeployer, waitForTransactions, wiresaw };
|
package/dist/internal.js
CHANGED
|
@@ -5,8 +5,9 @@ import {
|
|
|
5
5
|
debug
|
|
6
6
|
} from "./chunk-73UWXFXB.js";
|
|
7
7
|
import {
|
|
8
|
+
bigIntMax,
|
|
8
9
|
uniqueBy
|
|
9
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ETXWXV5T.js";
|
|
10
11
|
|
|
11
12
|
// src/waitForTransactions.ts
|
|
12
13
|
import { waitForTransactionReceipt } from "viem/actions";
|
|
@@ -59,6 +60,9 @@ async function ensureContract({
|
|
|
59
60
|
return [];
|
|
60
61
|
}
|
|
61
62
|
if (deployedBytecodeSize != null) {
|
|
63
|
+
if (deployedBytecodeSize === 0) {
|
|
64
|
+
throw new Error(`Empty bytecode for ${debugLabel}`);
|
|
65
|
+
}
|
|
62
66
|
if (deployedBytecodeSize > contractSizeLimit) {
|
|
63
67
|
console.warn(
|
|
64
68
|
`
|
|
@@ -198,12 +202,377 @@ function getContractAddress({
|
|
|
198
202
|
}) {
|
|
199
203
|
return getCreate2Address2({ from: deployerAddress, bytecode, salt });
|
|
200
204
|
}
|
|
205
|
+
|
|
206
|
+
// src/transports/methods/estimateUserOperationGas.ts
|
|
207
|
+
import {
|
|
208
|
+
decodeFunctionResult,
|
|
209
|
+
encodeFunctionData,
|
|
210
|
+
zeroAddress
|
|
211
|
+
} from "viem";
|
|
212
|
+
import {
|
|
213
|
+
entryPoint07Address,
|
|
214
|
+
formatUserOperation,
|
|
215
|
+
formatUserOperationRequest,
|
|
216
|
+
toPackedUserOperation
|
|
217
|
+
} from "viem/account-abstraction";
|
|
218
|
+
|
|
219
|
+
// src/transports/entryPointGasSimulations.ts
|
|
220
|
+
var entryPointGasSimulationsAbi = [
|
|
221
|
+
{
|
|
222
|
+
inputs: [
|
|
223
|
+
{
|
|
224
|
+
components: [
|
|
225
|
+
{
|
|
226
|
+
internalType: "address",
|
|
227
|
+
name: "sender",
|
|
228
|
+
type: "address"
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
internalType: "uint256",
|
|
232
|
+
name: "nonce",
|
|
233
|
+
type: "uint256"
|
|
234
|
+
},
|
|
235
|
+
{
|
|
236
|
+
internalType: "bytes",
|
|
237
|
+
name: "initCode",
|
|
238
|
+
type: "bytes"
|
|
239
|
+
},
|
|
240
|
+
{
|
|
241
|
+
internalType: "bytes",
|
|
242
|
+
name: "callData",
|
|
243
|
+
type: "bytes"
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
internalType: "bytes32",
|
|
247
|
+
name: "accountGasLimits",
|
|
248
|
+
type: "bytes32"
|
|
249
|
+
},
|
|
250
|
+
{
|
|
251
|
+
internalType: "uint256",
|
|
252
|
+
name: "preVerificationGas",
|
|
253
|
+
type: "uint256"
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
internalType: "bytes32",
|
|
257
|
+
name: "gasFees",
|
|
258
|
+
type: "bytes32"
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
internalType: "bytes",
|
|
262
|
+
name: "paymasterAndData",
|
|
263
|
+
type: "bytes"
|
|
264
|
+
},
|
|
265
|
+
{
|
|
266
|
+
internalType: "bytes",
|
|
267
|
+
name: "signature",
|
|
268
|
+
type: "bytes"
|
|
269
|
+
}
|
|
270
|
+
],
|
|
271
|
+
internalType: "struct PackedUserOperation",
|
|
272
|
+
name: "op",
|
|
273
|
+
type: "tuple"
|
|
274
|
+
}
|
|
275
|
+
],
|
|
276
|
+
name: "estimateGas",
|
|
277
|
+
outputs: [
|
|
278
|
+
{
|
|
279
|
+
components: [
|
|
280
|
+
{
|
|
281
|
+
internalType: "uint256",
|
|
282
|
+
name: "verificationGas",
|
|
283
|
+
type: "uint256"
|
|
284
|
+
},
|
|
285
|
+
{
|
|
286
|
+
internalType: "uint256",
|
|
287
|
+
name: "callGas",
|
|
288
|
+
type: "uint256"
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
internalType: "uint256",
|
|
292
|
+
name: "paymasterVerificationGas",
|
|
293
|
+
type: "uint256"
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
internalType: "uint256",
|
|
297
|
+
name: "paymasterPostOpGas",
|
|
298
|
+
type: "uint256"
|
|
299
|
+
}
|
|
300
|
+
],
|
|
301
|
+
internalType: "struct EntryPoint.GasInfo",
|
|
302
|
+
name: "",
|
|
303
|
+
type: "tuple"
|
|
304
|
+
}
|
|
305
|
+
],
|
|
306
|
+
stateMutability: "nonpayable",
|
|
307
|
+
type: "function"
|
|
308
|
+
}
|
|
309
|
+
];
|
|
310
|
+
|
|
311
|
+
// src/transports/methods/estimateUserOperationGas.ts
|
|
312
|
+
async function estimateUserOperationGas({
|
|
313
|
+
request,
|
|
314
|
+
params
|
|
315
|
+
}) {
|
|
316
|
+
const userOp = formatUserOperation(params[0]);
|
|
317
|
+
const gasSimulation = await simulateGas({ userOp, request });
|
|
318
|
+
const gasLimits = {
|
|
319
|
+
verificationGasLimit: gasSimulation.verificationGas * 2n,
|
|
320
|
+
callGasLimit: bigIntMax(gasSimulation.callGas * 2n, 9000n),
|
|
321
|
+
paymasterVerificationGasLimit: gasSimulation.paymasterVerificationGas * 2n,
|
|
322
|
+
paymasterPostOpGasLimit: gasSimulation.paymasterPostOpGas * 2n,
|
|
323
|
+
preVerificationGas: 20000n
|
|
324
|
+
};
|
|
325
|
+
return formatUserOperationRequest({
|
|
326
|
+
...gasLimits
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
async function simulateGas({ request, userOp }) {
|
|
330
|
+
const simulationUserOp = {
|
|
331
|
+
...userOp,
|
|
332
|
+
preVerificationGas: 0n,
|
|
333
|
+
callGasLimit: 10000000n,
|
|
334
|
+
verificationGasLimit: 10000000n,
|
|
335
|
+
// https://github.com/pimlicolabs/alto/blob/471998695e5ec75ef88dda3f8a534f47c24bcd1a/src/rpc/methods/eth_estimateUserOperationGas.ts#L117
|
|
336
|
+
maxPriorityFeePerGas: userOp.maxFeePerGas,
|
|
337
|
+
paymasterPostOpGasLimit: 2000000n,
|
|
338
|
+
paymasterVerificationGasLimit: 5000000n
|
|
339
|
+
};
|
|
340
|
+
const packedUserOp = toPackedUserOperation(simulationUserOp);
|
|
341
|
+
const simulationData = encodeFunctionData({
|
|
342
|
+
abi: entryPointGasSimulationsAbi,
|
|
343
|
+
functionName: "estimateGas",
|
|
344
|
+
args: [packedUserOp]
|
|
345
|
+
});
|
|
346
|
+
const hasPaymaster = userOp.paymaster != null && userOp.paymaster !== zeroAddress;
|
|
347
|
+
const senderBalanceOverride = hasPaymaster ? {} : { [userOp.sender]: { balance: "0xFFFFFFFFFFFFFFFFFFFF" } };
|
|
348
|
+
const simulationParams = [
|
|
349
|
+
{
|
|
350
|
+
to: entryPoint07Address,
|
|
351
|
+
data: simulationData
|
|
352
|
+
},
|
|
353
|
+
"pending",
|
|
354
|
+
{
|
|
355
|
+
...senderBalanceOverride
|
|
356
|
+
}
|
|
357
|
+
];
|
|
358
|
+
const encodedSimulationResult = await request({
|
|
359
|
+
method: "wiresaw_callEntryPointSimulations",
|
|
360
|
+
params: simulationParams
|
|
361
|
+
});
|
|
362
|
+
return decodeFunctionResult({
|
|
363
|
+
abi: entryPointGasSimulationsAbi,
|
|
364
|
+
functionName: "estimateGas",
|
|
365
|
+
data: encodedSimulationResult
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// src/transports/methods/getUserOperationReceipt.ts
|
|
370
|
+
import {
|
|
371
|
+
decodeEventLog,
|
|
372
|
+
encodeEventTopics,
|
|
373
|
+
numberToHex,
|
|
374
|
+
parseEventLogs,
|
|
375
|
+
zeroAddress as zeroAddress2
|
|
376
|
+
} from "viem";
|
|
377
|
+
import { entryPoint07Abi } from "viem/account-abstraction";
|
|
378
|
+
var userOperationRevertReasonAbi = [
|
|
379
|
+
entryPoint07Abi.find(
|
|
380
|
+
(item) => item.type === "event" && item.name === "UserOperationRevertReason"
|
|
381
|
+
)
|
|
382
|
+
];
|
|
383
|
+
var userOperationEventTopic = encodeEventTopics({
|
|
384
|
+
abi: entryPoint07Abi,
|
|
385
|
+
eventName: "UserOperationEvent"
|
|
386
|
+
});
|
|
387
|
+
function getUserOperationReceipt(userOpHash, receipt) {
|
|
388
|
+
const userOperationRevertReasonTopicEvent = encodeEventTopics({
|
|
389
|
+
abi: userOperationRevertReasonAbi
|
|
390
|
+
})[0];
|
|
391
|
+
let entryPoint = zeroAddress2;
|
|
392
|
+
let revertReason = void 0;
|
|
393
|
+
let startIndex = -1;
|
|
394
|
+
let endIndex = -1;
|
|
395
|
+
receipt.logs.forEach((log, index) => {
|
|
396
|
+
if (log?.topics[0] === userOperationEventTopic[0]) {
|
|
397
|
+
if (log.topics[1] === userOpHash) {
|
|
398
|
+
endIndex = index;
|
|
399
|
+
entryPoint = log.address;
|
|
400
|
+
} else if (endIndex === -1) {
|
|
401
|
+
startIndex = index;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (log?.topics[0] === userOperationRevertReasonTopicEvent) {
|
|
405
|
+
if (log.topics[1] === userOpHash) {
|
|
406
|
+
const decodedLog = decodeEventLog({
|
|
407
|
+
abi: userOperationRevertReasonAbi,
|
|
408
|
+
data: log.data,
|
|
409
|
+
topics: log.topics
|
|
410
|
+
});
|
|
411
|
+
revertReason = decodedLog.args.revertReason;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
if (endIndex === -1) {
|
|
416
|
+
throw new Error("fatal: no UserOperationEvent in logs");
|
|
417
|
+
}
|
|
418
|
+
const logs = receipt.logs.slice(startIndex + 1, endIndex);
|
|
419
|
+
const userOperationEvent = parseEventLogs({
|
|
420
|
+
abi: entryPoint07Abi,
|
|
421
|
+
eventName: "UserOperationEvent",
|
|
422
|
+
args: {
|
|
423
|
+
userOpHash
|
|
424
|
+
},
|
|
425
|
+
logs: receipt.logs
|
|
426
|
+
})[0];
|
|
427
|
+
let paymaster = userOperationEvent.args.paymaster;
|
|
428
|
+
paymaster = paymaster === zeroAddress2 ? void 0 : paymaster;
|
|
429
|
+
return {
|
|
430
|
+
userOpHash,
|
|
431
|
+
entryPoint,
|
|
432
|
+
sender: userOperationEvent.args.sender,
|
|
433
|
+
nonce: numberToHex(userOperationEvent.args.nonce),
|
|
434
|
+
paymaster,
|
|
435
|
+
actualGasUsed: numberToHex(userOperationEvent.args.actualGasUsed),
|
|
436
|
+
actualGasCost: numberToHex(userOperationEvent.args.actualGasCost),
|
|
437
|
+
success: userOperationEvent.args.success,
|
|
438
|
+
reason: revertReason,
|
|
439
|
+
logs,
|
|
440
|
+
receipt
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/transports/wiresaw.ts
|
|
445
|
+
function wiresaw(transport) {
|
|
446
|
+
return (opts) => {
|
|
447
|
+
const { request: originalRequest, ...rest } = transport.wiresaw(opts);
|
|
448
|
+
let chainId = null;
|
|
449
|
+
const transactionHashes = {};
|
|
450
|
+
const transactionReceipts = {};
|
|
451
|
+
return {
|
|
452
|
+
...rest,
|
|
453
|
+
// TODO: type `request` so we don't have to cast
|
|
454
|
+
async request(req) {
|
|
455
|
+
try {
|
|
456
|
+
if (req.method === "eth_chainId") {
|
|
457
|
+
if (chainId != null) return chainId;
|
|
458
|
+
if (transport.fallbackEth) {
|
|
459
|
+
const { request: fallbackRequest } = transport.fallbackEth(opts);
|
|
460
|
+
return chainId = await fallbackRequest(req);
|
|
461
|
+
}
|
|
462
|
+
return chainId = await originalRequest(req);
|
|
463
|
+
}
|
|
464
|
+
if (req.method === "eth_estimateGas") {
|
|
465
|
+
return await originalRequest({ ...req, method: "wiresaw_estimateGas" });
|
|
466
|
+
}
|
|
467
|
+
if (req.method === "eth_call") {
|
|
468
|
+
return await originalRequest({ ...req, method: "wiresaw_call" });
|
|
469
|
+
}
|
|
470
|
+
if (req.method === "eth_getTransactionCount") {
|
|
471
|
+
return await originalRequest({ ...req, method: "wiresaw_getTransactionCount" });
|
|
472
|
+
}
|
|
473
|
+
if (req.method === "eth_getTransactionReceipt") {
|
|
474
|
+
return await getTransactionReceipt(req.params[0]);
|
|
475
|
+
}
|
|
476
|
+
if (req.method === "eth_sendUserOperation") {
|
|
477
|
+
const { userOpHash, txHash } = await originalRequest({
|
|
478
|
+
...req,
|
|
479
|
+
method: "wiresaw_sendUserOperation"
|
|
480
|
+
});
|
|
481
|
+
transactionHashes[userOpHash] = txHash;
|
|
482
|
+
return userOpHash;
|
|
483
|
+
}
|
|
484
|
+
if (req.method === "eth_getUserOperationReceipt") {
|
|
485
|
+
const userOpHash = req.params[0];
|
|
486
|
+
const knownTransactionHash = transactionHashes[userOpHash];
|
|
487
|
+
if (knownTransactionHash) {
|
|
488
|
+
const transactionReceipt = await getTransactionReceipt(knownTransactionHash);
|
|
489
|
+
if (transactionReceipt) {
|
|
490
|
+
return getUserOperationReceipt(userOpHash, transactionReceipt);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (transport.fallbackBundler) {
|
|
494
|
+
const { request: fallbackRequest } = transport.fallbackBundler(opts);
|
|
495
|
+
return await fallbackRequest(req);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (req.method === "eth_estimateUserOperationGas") {
|
|
499
|
+
try {
|
|
500
|
+
return await estimateUserOperationGas({
|
|
501
|
+
request: originalRequest,
|
|
502
|
+
params: req.params
|
|
503
|
+
});
|
|
504
|
+
} catch (e) {
|
|
505
|
+
console.warn("[wiresaw] estimating user operation gas failed, falling back to bundler", e);
|
|
506
|
+
}
|
|
507
|
+
if (transport.fallbackBundler) {
|
|
508
|
+
const { request: fallbackRequest } = transport.fallbackBundler(opts);
|
|
509
|
+
return await fallbackRequest(req);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (req.method === "eth_blockNumber" || req.method === "eth_getBlockByNumber" || req.method === "eth_maxPriorityFeePerGas") {
|
|
513
|
+
if (transport.fallbackEth) {
|
|
514
|
+
const { request: fallbackRequest } = transport.fallbackEth(opts);
|
|
515
|
+
return await fallbackRequest(req);
|
|
516
|
+
}
|
|
517
|
+
return await originalRequest(req);
|
|
518
|
+
}
|
|
519
|
+
return await originalRequest(req);
|
|
520
|
+
} catch (e) {
|
|
521
|
+
console.warn("[wiresaw] request error", e);
|
|
522
|
+
const bundlerMethods = [
|
|
523
|
+
"eth_estimateUserOperationGas",
|
|
524
|
+
"eth_sendUserOperation",
|
|
525
|
+
"eth_getUserOperationReceipt"
|
|
526
|
+
];
|
|
527
|
+
if (bundlerMethods.includes(req.method)) {
|
|
528
|
+
if (transport.fallbackBundler) {
|
|
529
|
+
const { request: fallbackRequest } = transport.fallbackBundler(opts);
|
|
530
|
+
console.warn("[wiresaw] falling back to bundler rpc", req);
|
|
531
|
+
return fallbackRequest(req);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (transport.fallbackEth) {
|
|
535
|
+
const { request: fallbackRequest } = transport.fallbackEth(opts);
|
|
536
|
+
console.warn("[wiresaw] falling back to eth rpc", req);
|
|
537
|
+
return fallbackRequest(req);
|
|
538
|
+
}
|
|
539
|
+
throw e;
|
|
540
|
+
}
|
|
541
|
+
async function getTransactionReceipt(hash) {
|
|
542
|
+
if (transactionReceipts[hash]) return transactionReceipts[hash];
|
|
543
|
+
const pendingReceipt = await originalRequest({
|
|
544
|
+
...req,
|
|
545
|
+
method: "wiresaw_getTransactionReceipt",
|
|
546
|
+
params: [hash]
|
|
547
|
+
});
|
|
548
|
+
if (pendingReceipt) {
|
|
549
|
+
transactionReceipts[hash] = pendingReceipt;
|
|
550
|
+
return pendingReceipt;
|
|
551
|
+
}
|
|
552
|
+
if (transport.fallbackEth) {
|
|
553
|
+
const { request: fallbackRequest } = transport.fallbackEth(opts);
|
|
554
|
+
const receipt = await fallbackRequest({
|
|
555
|
+
...req,
|
|
556
|
+
method: "eth_getTransactionReceipt",
|
|
557
|
+
params: [hash]
|
|
558
|
+
});
|
|
559
|
+
if (receipt) {
|
|
560
|
+
transactionReceipts[hash] = receipt;
|
|
561
|
+
return receipt;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
};
|
|
568
|
+
}
|
|
201
569
|
export {
|
|
202
570
|
ensureContract,
|
|
203
571
|
ensureContractsDeployed,
|
|
204
572
|
ensureDeployer,
|
|
205
573
|
getContractAddress,
|
|
206
574
|
getDeployer,
|
|
207
|
-
waitForTransactions
|
|
575
|
+
waitForTransactions,
|
|
576
|
+
wiresaw
|
|
208
577
|
};
|
|
209
578
|
//# sourceMappingURL=internal.js.map
|
package/dist/internal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/waitForTransactions.ts","../src/deploy/ensureContract.ts","../src/deploy/common.ts","../src/deploy/debug.ts","../src/deploy/ensureContractsDeployed.ts","../src/deploy/ensureDeployer.ts","../src/deploy/create2/deployment.json","../src/deploy/getDeployer.ts","../src/deploy/getContractAddress.ts"],"sourcesContent":["import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { debug } from \"./debug\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\n\nexport async function waitForTransactions({\n client,\n hashes,\n debugLabel = \"transactions\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly hashes: readonly Hex[];\n readonly debugLabel?: string;\n}): Promise<void> {\n if (!hashes.length) return;\n\n debug(`waiting for ${debugLabel} to confirm`);\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const hash of hashes) {\n const receipt = await waitForTransactionReceipt(client, { hash });\n // TODO: handle user op failures?\n if (receipt.status === \"reverted\") {\n throw new Error(`Transaction reverted: ${hash}`);\n }\n }\n}\n","import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport { contractSizeLimit, singletonSalt } from \"./common\";\nimport { debug } from \"./debug\";\nimport { sendTransaction } from \"../sendTransaction\";\n\nexport type Contract = {\n bytecode: Hex;\n deployedBytecodeSize?: number;\n debugLabel?: string;\n salt?: Hex;\n};\n\nexport async function ensureContract({\n client,\n deployerAddress,\n bytecode,\n deployedBytecodeSize,\n debugLabel = \"contract\",\n salt = singletonSalt,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n} & Contract): Promise<readonly Hex[]> {\n if (bytecode.includes(\"__$\")) {\n throw new Error(`Found unlinked public library in ${debugLabel} bytecode`);\n }\n\n const address = getCreate2Address({ from: deployerAddress, salt, bytecode });\n\n const contractCode = await getCode(client, { address, blockTag: \"pending\" });\n if (contractCode) {\n debug(\"found\", debugLabel, \"at\", address);\n return [];\n }\n\n if (deployedBytecodeSize != null) {\n if (deployedBytecodeSize > contractSizeLimit) {\n console.warn(\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n }\n }\n\n debug(\"deploying\", debugLabel, \"at\", address);\n return [\n await sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployerAddress,\n data: concatHex([salt, bytecode]),\n }),\n ];\n}\n","import { stringToHex } from \"viem\";\n\n// salt for deterministic deploys of singleton contracts\nexport const singletonSalt = stringToHex(\"\", { size: 32 });\n\n// https://eips.ethereum.org/EIPS/eip-170\nexport const contractSizeLimit = parseInt(\"6000\", 16);\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\nexport const error = parentDebug.extend(\"deploy\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { Contract, ensureContract } from \"./ensureContract\";\nimport { waitForTransactions } from \"../waitForTransactions\";\nimport { uniqueBy } from \"../utils/uniqueBy\";\n\nexport async function ensureContractsDeployed({\n client,\n deployerAddress,\n contracts,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly contracts: readonly Contract[];\n}): Promise<readonly Hex[]> {\n // Deployments assume a deterministic deployer, so we only need to deploy the unique bytecode\n const uniqueContracts = uniqueBy(contracts, (contract) => contract.bytecode);\n\n const txs = (\n await Promise.all(uniqueContracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))\n ).flat();\n\n await waitForTransactions({\n client,\n hashes: txs,\n debugLabel: \"contract deploys\",\n });\n\n return txs;\n}\n","import { Account, Address, Chain, Client, Transport } from \"viem\";\nimport { getBalance, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\nimport { getDeployer } from \"./getDeployer\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {\n const existingDeployer = await getDeployer(client);\n if (existingDeployer !== undefined) {\n return existingDeployer;\n }\n\n // There's not really a way to simulate a pre-EIP-155 (no chain ID) transaction,\n // so we have to attempt to create the deployer first and, if it fails, fall back\n // to a regular deploy.\n\n // Send gas to deployment signer\n const gasRequired = BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice);\n const currentBalance = await getBalance(client, { address: `0x${deployment.signerAddress}` });\n const gasNeeded = gasRequired - currentBalance;\n if (gasNeeded > 0) {\n debug(\"sending gas for CREATE2 deployer to signer at\", deployment.signerAddress);\n const gasTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n to: `0x${deployment.signerAddress}`,\n value: gasNeeded,\n });\n const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });\n if (gasReceipt.status !== \"success\") {\n console.error(\"failed to send gas to deployer signer\", gasReceipt);\n throw new Error(\"failed to send gas to deployer signer\");\n }\n }\n\n // Deploy the deployer\n debug(\"deploying CREATE2 deployer at\", deployer);\n const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` }).catch(\n (error) => {\n // Do a regular contract create if the presigned transaction doesn't work due to replay protection\n if (String(error).includes(\"only replay-protected (EIP-155) transactions allowed over RPC\")) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\n ⚠️ Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.\\n\\n We recommend running your chain's node with \\`--rpc.allow-unprotected-txs\\` to enable determinstic deployments.\\n`,\n );\n debug(\"deploying CREATE2 deployer\");\n return sendTransaction(client, {\n chain: client.chain ?? null,\n data: `0x${deployment.creationCode}`,\n });\n }\n throw error;\n },\n );\n\n const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (!deployReceipt.contractAddress) {\n throw new Error(\"Deploy receipt did not have contract address, was the deployer not deployed?\");\n }\n\n if (deployReceipt.contractAddress !== deployer) {\n console.warn(\n `\\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`,\n );\n }\n\n return deployReceipt.contractAddress;\n}\n","{\n \"gasPrice\": 100000000000,\n \"gasLimit\": 100000,\n \"signerAddress\": \"3fab184622dc19b6109349b94811493bf2a45362\",\n \"transaction\": \"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222\",\n \"address\": \"4e59b44847b379578588920ca78fbf26c0b4956c\",\n \"creationCode\": \"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3\"\n}\n","import { Address, Chain, Client, Transport, sliceHex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined> {\n const bytecode = await getCode(client, { address: deployer });\n if (bytecode) {\n debug(\"found deployer bytecode at\", deployer);\n // check if deployed bytecode is the same as the expected bytecode (minus 14-bytes creation code prefix)\n if (bytecode !== sliceHex(`0x${deployment.creationCode}`, 14)) {\n console.warn(\n `\\n ⚠️ Bytecode for deployer at ${deployer} did not match the expected CREATE2 bytecode. You may have unexpected results.\\n`,\n );\n }\n return deployer;\n }\n}\n","import { Hex, getCreate2Address } from \"viem\";\nimport { singletonSalt } from \"./common\";\n\nexport function getContractAddress({\n deployerAddress,\n bytecode,\n salt = singletonSalt,\n}: {\n readonly deployerAddress: Hex;\n readonly bytecode: Hex;\n readonly salt?: Hex;\n}): Hex {\n return getCreate2Address({ from: deployerAddress, bytecode, salt });\n}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AAA,UAC7B,OAAO,OAAO,SAAS;AAAA,UACvB,MAAM,KAAK,mBAAW,YAAY;AAAA,QACpC,CAAC;AAAA,MACH;AACA,YAAME;AAAA,IACR;AAAA,EACF;AAEA,QAAM,gBAAgB,MAAMD,2BAA0B,QAAQ,EAAE,MAAM,SAAS,CAAC;AAChF,MAAI,CAAC,cAAc,iBAAiB;AAClC,UAAM,IAAI,MAAM,8EAA8E;AAAA,EAChG;AAEA,MAAI,cAAc,oBAAoBH,WAAU;AAC9C,YAAQ;AAAA,MACN;AAAA,6CAAsC,cAAc,eAAe,kEAAkEA,SAAQ;AAAA,IAC/I;AAAA,EACF;AAEA,SAAO,cAAc;AACvB;;;AGpEA,SAAc,qBAAAK,0BAAyB;AAGhC,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA,OAAO;AACT,GAIQ;AACN,SAAOC,mBAAkB,EAAE,MAAM,iBAAiB,UAAU,KAAK,CAAC;AACpE;","names":["debug","debug","sendTransaction","waitForTransactionReceipt","getCode","getCode","debug","deployer","debug","sendTransaction","waitForTransactionReceipt","error","getCreate2Address","getCreate2Address"]}
|
|
1
|
+
{"version":3,"sources":["../src/waitForTransactions.ts","../src/deploy/ensureContract.ts","../src/deploy/common.ts","../src/deploy/debug.ts","../src/deploy/ensureContractsDeployed.ts","../src/deploy/ensureDeployer.ts","../src/deploy/create2/deployment.json","../src/deploy/getDeployer.ts","../src/deploy/getContractAddress.ts","../src/transports/methods/estimateUserOperationGas.ts","../src/transports/entryPointGasSimulations.ts","../src/transports/methods/getUserOperationReceipt.ts","../src/transports/wiresaw.ts"],"sourcesContent":["import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { debug } from \"./debug\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\n\nexport async function waitForTransactions({\n client,\n hashes,\n debugLabel = \"transactions\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly hashes: readonly Hex[];\n readonly debugLabel?: string;\n}): Promise<void> {\n if (!hashes.length) return;\n\n debug(`waiting for ${debugLabel} to confirm`);\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const hash of hashes) {\n const receipt = await waitForTransactionReceipt(client, { hash });\n // TODO: handle user op failures?\n if (receipt.status === \"reverted\") {\n throw new Error(`Transaction reverted: ${hash}`);\n }\n }\n}\n","import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport { contractSizeLimit, singletonSalt } from \"./common\";\nimport { debug } from \"./debug\";\nimport { sendTransaction } from \"../sendTransaction\";\n\nexport type Contract = {\n bytecode: Hex;\n deployedBytecodeSize?: number;\n debugLabel?: string;\n salt?: Hex;\n};\n\nexport async function ensureContract({\n client,\n deployerAddress,\n bytecode,\n deployedBytecodeSize,\n debugLabel = \"contract\",\n salt = singletonSalt,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n} & Contract): Promise<readonly Hex[]> {\n if (bytecode.includes(\"__$\")) {\n throw new Error(`Found unlinked public library in ${debugLabel} bytecode`);\n }\n\n const address = getCreate2Address({ from: deployerAddress, salt, bytecode });\n\n const contractCode = await getCode(client, { address, blockTag: \"pending\" });\n if (contractCode) {\n debug(\"found\", debugLabel, \"at\", address);\n return [];\n }\n\n if (deployedBytecodeSize != null) {\n if (deployedBytecodeSize === 0) {\n throw new Error(`Empty bytecode for ${debugLabel}`);\n }\n\n if (deployedBytecodeSize > contractSizeLimit) {\n console.warn(\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n }\n }\n\n debug(\"deploying\", debugLabel, \"at\", address);\n return [\n await sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployerAddress,\n data: concatHex([salt, bytecode]),\n }),\n ];\n}\n","import { stringToHex } from \"viem\";\n\n// salt for deterministic deploys of singleton contracts\nexport const singletonSalt = stringToHex(\"\", { size: 32 });\n\n// https://eips.ethereum.org/EIPS/eip-170\nexport const contractSizeLimit = parseInt(\"6000\", 16);\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\nexport const error = parentDebug.extend(\"deploy\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { Contract, ensureContract } from \"./ensureContract\";\nimport { waitForTransactions } from \"../waitForTransactions\";\nimport { uniqueBy } from \"../utils/uniqueBy\";\n\nexport async function ensureContractsDeployed({\n client,\n deployerAddress,\n contracts,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly contracts: readonly Contract[];\n}): Promise<readonly Hex[]> {\n // Deployments assume a deterministic deployer, so we only need to deploy the unique bytecode\n const uniqueContracts = uniqueBy(contracts, (contract) => contract.bytecode);\n\n const txs = (\n await Promise.all(uniqueContracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))\n ).flat();\n\n await waitForTransactions({\n client,\n hashes: txs,\n debugLabel: \"contract deploys\",\n });\n\n return txs;\n}\n","import { Account, Address, Chain, Client, Transport } from \"viem\";\nimport { getBalance, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\nimport { getDeployer } from \"./getDeployer\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {\n const existingDeployer = await getDeployer(client);\n if (existingDeployer !== undefined) {\n return existingDeployer;\n }\n\n // There's not really a way to simulate a pre-EIP-155 (no chain ID) transaction,\n // so we have to attempt to create the deployer first and, if it fails, fall back\n // to a regular deploy.\n\n // Send gas to deployment signer\n const gasRequired = BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice);\n const currentBalance = await getBalance(client, { address: `0x${deployment.signerAddress}` });\n const gasNeeded = gasRequired - currentBalance;\n if (gasNeeded > 0) {\n debug(\"sending gas for CREATE2 deployer to signer at\", deployment.signerAddress);\n const gasTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n to: `0x${deployment.signerAddress}`,\n value: gasNeeded,\n });\n const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });\n if (gasReceipt.status !== \"success\") {\n console.error(\"failed to send gas to deployer signer\", gasReceipt);\n throw new Error(\"failed to send gas to deployer signer\");\n }\n }\n\n // Deploy the deployer\n debug(\"deploying CREATE2 deployer at\", deployer);\n const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` }).catch(\n (error) => {\n // Do a regular contract create if the presigned transaction doesn't work due to replay protection\n if (String(error).includes(\"only replay-protected (EIP-155) transactions allowed over RPC\")) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\n ⚠️ Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.\\n\\n We recommend running your chain's node with \\`--rpc.allow-unprotected-txs\\` to enable determinstic deployments.\\n`,\n );\n debug(\"deploying CREATE2 deployer\");\n return sendTransaction(client, {\n chain: client.chain ?? null,\n data: `0x${deployment.creationCode}`,\n });\n }\n throw error;\n },\n );\n\n const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (!deployReceipt.contractAddress) {\n throw new Error(\"Deploy receipt did not have contract address, was the deployer not deployed?\");\n }\n\n if (deployReceipt.contractAddress !== deployer) {\n console.warn(\n `\\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`,\n );\n }\n\n return deployReceipt.contractAddress;\n}\n","{\n \"gasPrice\": 100000000000,\n \"gasLimit\": 100000,\n \"signerAddress\": \"3fab184622dc19b6109349b94811493bf2a45362\",\n \"transaction\": \"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222\",\n \"address\": \"4e59b44847b379578588920ca78fbf26c0b4956c\",\n \"creationCode\": \"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3\"\n}\n","import { Address, Chain, Client, Transport, sliceHex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined> {\n const bytecode = await getCode(client, { address: deployer });\n if (bytecode) {\n debug(\"found deployer bytecode at\", deployer);\n // check if deployed bytecode is the same as the expected bytecode (minus 14-bytes creation code prefix)\n if (bytecode !== sliceHex(`0x${deployment.creationCode}`, 14)) {\n console.warn(\n `\\n ⚠️ Bytecode for deployer at ${deployer} did not match the expected CREATE2 bytecode. You may have unexpected results.\\n`,\n );\n }\n return deployer;\n }\n}\n","import { Hex, getCreate2Address } from \"viem\";\nimport { singletonSalt } from \"./common\";\n\nexport function getContractAddress({\n deployerAddress,\n bytecode,\n salt = singletonSalt,\n}: {\n readonly deployerAddress: Hex;\n readonly bytecode: Hex;\n readonly salt?: Hex;\n}): Hex {\n return getCreate2Address({ from: deployerAddress, bytecode, salt });\n}\n","import {\n BundlerRpcSchema,\n decodeFunctionResult,\n DecodeFunctionResultReturnType,\n EIP1193RequestFn,\n encodeFunctionData,\n Hex,\n zeroAddress,\n} from \"viem\";\nimport { getRpcMethod } from \"../common\";\nimport {\n entryPoint07Address,\n formatUserOperation,\n formatUserOperationRequest,\n toPackedUserOperation,\n UserOperation,\n} from \"viem/account-abstraction\";\nimport { bigIntMax } from \"../../utils\";\nimport { entryPointGasSimulationsAbi } from \"../entryPointGasSimulations\";\n\ntype rpcMethod = getRpcMethod<BundlerRpcSchema, \"eth_estimateUserOperationGas\">;\n\ntype EstimateUserOperationGasOptions = {\n request: EIP1193RequestFn;\n params: rpcMethod[\"Parameters\"];\n};\n\nexport async function estimateUserOperationGas({\n request,\n params,\n}: EstimateUserOperationGasOptions): Promise<rpcMethod[\"ReturnType\"]> {\n const userOp = formatUserOperation(params[0]);\n const gasSimulation = await simulateGas({ userOp, request });\n const gasLimits = {\n verificationGasLimit: gasSimulation.verificationGas * 2n,\n callGasLimit: bigIntMax(gasSimulation.callGas * 2n, 9000n),\n paymasterVerificationGasLimit: gasSimulation.paymasterVerificationGas * 2n,\n paymasterPostOpGasLimit: gasSimulation.paymasterPostOpGas * 2n,\n preVerificationGas: 20_000n,\n };\n\n return formatUserOperationRequest({\n ...gasLimits,\n });\n}\n\ntype SimulateGasOptions = {\n request: EIP1193RequestFn;\n userOp: UserOperation<\"0.7\">;\n};\n\ntype SimulateGasResult = DecodeFunctionResultReturnType<typeof entryPointGasSimulationsAbi>;\n\nasync function simulateGas({ request, userOp }: SimulateGasOptions): Promise<SimulateGasResult> {\n // Prepare user operation for simulation\n const simulationUserOp = {\n ...userOp,\n preVerificationGas: 0n,\n callGasLimit: 10_000_000n,\n verificationGasLimit: 10_000_000n,\n // https://github.com/pimlicolabs/alto/blob/471998695e5ec75ef88dda3f8a534f47c24bcd1a/src/rpc/methods/eth_estimateUserOperationGas.ts#L117\n maxPriorityFeePerGas: userOp.maxFeePerGas,\n paymasterPostOpGasLimit: 2_000_000n,\n paymasterVerificationGasLimit: 5_000_000n,\n } satisfies UserOperation<\"0.7\">;\n\n const packedUserOp = toPackedUserOperation(simulationUserOp);\n const simulationData = encodeFunctionData({\n abi: entryPointGasSimulationsAbi,\n functionName: \"estimateGas\",\n args: [packedUserOp],\n });\n\n const hasPaymaster = userOp.paymaster != null && userOp.paymaster !== zeroAddress;\n const senderBalanceOverride = hasPaymaster ? {} : { [userOp.sender]: { balance: \"0xFFFFFFFFFFFFFFFFFFFF\" } };\n const simulationParams = [\n {\n to: entryPoint07Address,\n data: simulationData,\n },\n \"pending\",\n {\n ...senderBalanceOverride,\n },\n ];\n const encodedSimulationResult: Hex = await request({\n method: \"wiresaw_callEntryPointSimulations\",\n params: simulationParams,\n });\n\n return decodeFunctionResult({\n abi: entryPointGasSimulationsAbi,\n functionName: \"estimateGas\",\n data: encodedSimulationResult,\n });\n}\n","export const entryPointGasSimulationsAbi = [\n {\n inputs: [\n {\n components: [\n {\n internalType: \"address\",\n name: \"sender\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"nonce\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"initCode\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes\",\n name: \"callData\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes32\",\n name: \"accountGasLimits\",\n type: \"bytes32\",\n },\n {\n internalType: \"uint256\",\n name: \"preVerificationGas\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes32\",\n name: \"gasFees\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"paymasterAndData\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes\",\n name: \"signature\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct PackedUserOperation\",\n name: \"op\",\n type: \"tuple\",\n },\n ],\n name: \"estimateGas\",\n outputs: [\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"verificationGas\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"callGas\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"paymasterVerificationGas\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"paymasterPostOpGas\",\n type: \"uint256\",\n },\n ],\n internalType: \"struct EntryPoint.GasInfo\",\n name: \"\",\n type: \"tuple\",\n },\n ],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n] as const;\n","import {\n Address,\n ExtractAbiItem,\n Hex,\n RpcTransactionReceipt,\n RpcUserOperationReceipt,\n decodeEventLog,\n encodeEventTopics,\n numberToHex,\n parseEventLogs,\n zeroAddress,\n} from \"viem\";\nimport { entryPoint07Abi } from \"viem/account-abstraction\";\n\nconst userOperationRevertReasonAbi = [\n entryPoint07Abi.find(\n (item): item is ExtractAbiItem<typeof entryPoint07Abi, \"UserOperationRevertReason\"> =>\n item.type === \"event\" && item.name === \"UserOperationRevertReason\",\n )!,\n] as const;\n\nconst userOperationEventTopic = encodeEventTopics({\n abi: entryPoint07Abi,\n eventName: \"UserOperationEvent\",\n});\n\nexport function getUserOperationReceipt(userOpHash: Hex, receipt: RpcTransactionReceipt): RpcUserOperationReceipt {\n const userOperationRevertReasonTopicEvent = encodeEventTopics({\n abi: userOperationRevertReasonAbi,\n })[0];\n\n let entryPoint: Address = zeroAddress;\n let revertReason = undefined;\n\n let startIndex = -1;\n let endIndex = -1;\n receipt.logs.forEach((log, index) => {\n if (log?.topics[0] === userOperationEventTopic[0]) {\n // process UserOperationEvent\n if (log.topics[1] === userOpHash) {\n // it's our userOpHash. save as end of logs array\n endIndex = index;\n entryPoint = log.address;\n } else if (endIndex === -1) {\n // it's a different hash. remember it as beginning index, but only if we didn't find our end index yet.\n startIndex = index;\n }\n }\n\n if (log?.topics[0] === userOperationRevertReasonTopicEvent) {\n // process UserOperationRevertReason\n if (log.topics[1] === userOpHash) {\n // it's our userOpHash. capture revert reason.\n const decodedLog = decodeEventLog({\n abi: userOperationRevertReasonAbi,\n data: log.data,\n topics: log.topics,\n });\n\n revertReason = decodedLog.args.revertReason;\n }\n }\n });\n\n if (endIndex === -1) {\n throw new Error(\"fatal: no UserOperationEvent in logs\");\n }\n\n const logs = receipt.logs.slice(startIndex + 1, endIndex);\n\n const userOperationEvent = parseEventLogs({\n abi: entryPoint07Abi,\n eventName: \"UserOperationEvent\",\n args: {\n userOpHash,\n },\n logs: receipt.logs,\n })[0]!;\n\n let paymaster: Address | undefined = userOperationEvent.args.paymaster;\n paymaster = paymaster === zeroAddress ? undefined : paymaster;\n\n return {\n userOpHash,\n entryPoint,\n sender: userOperationEvent.args.sender,\n nonce: numberToHex(userOperationEvent.args.nonce),\n paymaster,\n actualGasUsed: numberToHex(userOperationEvent.args.actualGasUsed),\n actualGasCost: numberToHex(userOperationEvent.args.actualGasCost),\n success: userOperationEvent.args.success,\n reason: revertReason,\n logs,\n receipt,\n };\n}\n","import { EIP1193RequestFn, Hex, RpcTransactionReceipt, Transport } from \"viem\";\nimport { estimateUserOperationGas } from \"./methods/estimateUserOperationGas\";\nimport { getUserOperationReceipt } from \"./methods/getUserOperationReceipt\";\n\ntype WiresawSendUserOperationResult = {\n txHash: Hex;\n userOpHash: Hex;\n};\n\ntype WiresawOptions<transport extends Transport> = {\n wiresaw: transport;\n fallbackBundler?: Transport;\n fallbackEth?: Transport;\n};\n\nexport function wiresaw<const wiresawTransport extends Transport>(\n transport: WiresawOptions<wiresawTransport>,\n): wiresawTransport {\n return ((opts) => {\n const { request: originalRequest, ...rest } = transport.wiresaw(opts);\n\n let chainId: Hex | null = null;\n const transactionHashes: { [userOpHash: Hex]: Hex } = {};\n const transactionReceipts: { [transactionHashes: Hex]: RpcTransactionReceipt } = {};\n\n return {\n ...rest,\n // TODO: type `request` so we don't have to cast\n async request(req): ReturnType<EIP1193RequestFn> {\n try {\n if (req.method === \"eth_chainId\") {\n if (chainId != null) return chainId;\n if (transport.fallbackEth) {\n const { request: fallbackRequest } = transport.fallbackEth(opts);\n return (chainId = await fallbackRequest(req));\n }\n return (chainId = await originalRequest(req));\n }\n\n if (req.method === \"eth_estimateGas\") {\n return await originalRequest({ ...req, method: \"wiresaw_estimateGas\" });\n }\n\n if (req.method === \"eth_call\") {\n return await originalRequest({ ...req, method: \"wiresaw_call\" });\n }\n\n if (req.method === \"eth_getTransactionCount\") {\n return await originalRequest({ ...req, method: \"wiresaw_getTransactionCount\" });\n }\n\n if (req.method === \"eth_getTransactionReceipt\") {\n return await getTransactionReceipt((req.params as [Hex])[0]);\n }\n\n if (req.method === \"eth_sendUserOperation\") {\n const { userOpHash, txHash } = (await originalRequest({\n ...req,\n method: \"wiresaw_sendUserOperation\",\n })) as WiresawSendUserOperationResult;\n transactionHashes[userOpHash] = txHash;\n return userOpHash;\n }\n\n if (req.method === \"eth_getUserOperationReceipt\") {\n const userOpHash = (req.params as [Hex])[0];\n const knownTransactionHash = transactionHashes[userOpHash];\n if (knownTransactionHash) {\n const transactionReceipt = await getTransactionReceipt(knownTransactionHash);\n if (transactionReceipt) {\n return getUserOperationReceipt(userOpHash, transactionReceipt);\n }\n }\n if (transport.fallbackBundler) {\n const { request: fallbackRequest } = transport.fallbackBundler(opts);\n return await fallbackRequest(req);\n }\n }\n\n if (req.method === \"eth_estimateUserOperationGas\") {\n try {\n return await estimateUserOperationGas({\n request: originalRequest,\n params: req.params as never,\n });\n } catch (e) {\n console.warn(\"[wiresaw] estimating user operation gas failed, falling back to bundler\", e);\n }\n\n if (transport.fallbackBundler) {\n const { request: fallbackRequest } = transport.fallbackBundler(opts);\n return await fallbackRequest(req);\n }\n }\n\n // Fallback to regular RPC for methods that don't require wiresaw\n if (\n req.method === \"eth_blockNumber\" ||\n req.method === \"eth_getBlockByNumber\" ||\n req.method === \"eth_maxPriorityFeePerGas\"\n ) {\n if (transport.fallbackEth) {\n const { request: fallbackRequest } = transport.fallbackEth(opts);\n return await fallbackRequest(req);\n }\n return await originalRequest(req);\n }\n\n return await originalRequest(req);\n } catch (e) {\n console.warn(\"[wiresaw] request error\", e);\n const bundlerMethods = [\n \"eth_estimateUserOperationGas\",\n \"eth_sendUserOperation\",\n \"eth_getUserOperationReceipt\",\n ];\n if (bundlerMethods.includes(req.method)) {\n if (transport.fallbackBundler) {\n const { request: fallbackRequest } = transport.fallbackBundler(opts);\n console.warn(\"[wiresaw] falling back to bundler rpc\", req);\n return fallbackRequest(req);\n }\n }\n if (transport.fallbackEth) {\n const { request: fallbackRequest } = transport.fallbackEth(opts);\n console.warn(\"[wiresaw] falling back to eth rpc\", req);\n return fallbackRequest(req);\n }\n throw e;\n }\n\n async function getTransactionReceipt(hash: Hex): Promise<RpcTransactionReceipt | undefined> {\n // Return cached receipt if available\n if (transactionReceipts[hash]) return transactionReceipts[hash];\n\n // Fetch pending receipt\n const pendingReceipt = (await originalRequest({\n ...req,\n method: \"wiresaw_getTransactionReceipt\",\n params: [hash],\n })) as RpcTransactionReceipt | undefined;\n if (pendingReceipt) {\n transactionReceipts[hash] = pendingReceipt;\n return pendingReceipt;\n }\n\n if (transport.fallbackEth) {\n const { request: fallbackRequest } = transport.fallbackEth(opts);\n const receipt = (await fallbackRequest({\n ...req,\n method: \"eth_getTransactionReceipt\",\n params: [hash],\n })) as RpcTransactionReceipt | undefined;\n if (receipt) {\n transactionReceipts[hash] = receipt;\n return receipt;\n }\n }\n }\n },\n };\n }) as wiresawTransport;\n}\n"],"mappings":";;;;;;;;;;;;AAEA,SAAS,iCAAiC;AAE1C,eAAsB,oBAAoB;AAAA,EACxC;AAAA,EACA;AAAA,EACA,aAAa;AACf,GAIkB;AAChB,MAAI,CAAC,OAAO,OAAQ;AAEpB,QAAM,eAAe,UAAU,aAAa;AAE5C,aAAW,QAAQ,QAAQ;AACzB,UAAM,UAAU,MAAM,0BAA0B,QAAQ,EAAE,KAAK,CAAC;AAEhE,QAAI,QAAQ,WAAW,YAAY;AACjC,YAAM,IAAI,MAAM,yBAAyB,IAAI,EAAE;AAAA,IACjD;AAAA,EACF;AACF;;;ACxBA,SAA4C,WAAW,yBAA8B;AACrF,SAAS,eAAe;;;ACDxB,SAAS,mBAAmB;AAGrB,IAAM,gBAAgB,YAAY,IAAI,EAAE,MAAM,GAAG,CAAC;AAGlD,IAAM,oBAAoB,SAAS,QAAQ,EAAE;;;ACJ7C,IAAMA,SAAQ,MAAY,OAAO,QAAQ;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AACzB,kBAAM,EAAE,SAAS,gBAAgB,IAAI,UAAU,YAAY,IAAI;AAC/D,kBAAM,UAAW,MAAM,gBAAgB;AAAA,cACrC,GAAG;AAAA,cACH,QAAQ;AAAA,cACR,QAAQ,CAAC,IAAI;AAAA,YACf,CAAC;AACD,gBAAI,SAAS;AACX,kCAAoB,IAAI,IAAI;AAC5B,qBAAO;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["debug","debug","sendTransaction","waitForTransactionReceipt","getCode","getCode","debug","deployer","debug","sendTransaction","waitForTransactionReceipt","error","getCreate2Address","getCreate2Address","zeroAddress"]}
|
package/dist/utils.js
CHANGED
|
@@ -13,12 +13,10 @@ import {
|
|
|
13
13
|
iteratorToArray,
|
|
14
14
|
mapObject,
|
|
15
15
|
unique,
|
|
16
|
+
uniqueBy,
|
|
16
17
|
wait,
|
|
17
18
|
waitForIdle
|
|
18
|
-
} from "./chunk-
|
|
19
|
-
import {
|
|
20
|
-
uniqueBy
|
|
21
|
-
} from "./chunk-CHXZROA7.js";
|
|
19
|
+
} from "./chunk-ETXWXV5T.js";
|
|
22
20
|
export {
|
|
23
21
|
assertExhaustive,
|
|
24
22
|
bigIntMax,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@latticexyz/common",
|
|
3
|
-
"version": "2.2.22-
|
|
3
|
+
"version": "2.2.22-d59c81524363756c6fd68dc696e996d8675eb095",
|
|
4
4
|
"description": "Common low level logic shared between packages",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -69,11 +69,11 @@
|
|
|
69
69
|
"p-retry": "^5.1.2",
|
|
70
70
|
"prettier": "3.2.5",
|
|
71
71
|
"prettier-plugin-solidity": "1.3.1",
|
|
72
|
-
"@latticexyz/schema-type": "2.2.22-
|
|
72
|
+
"@latticexyz/schema-type": "2.2.22-d59c81524363756c6fd68dc696e996d8675eb095"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@types/debug": "^4.1.7",
|
|
76
|
-
"viem": "2.
|
|
76
|
+
"viem": "2.30.6"
|
|
77
77
|
},
|
|
78
78
|
"peerDependencies": {
|
|
79
79
|
"@aws-sdk/client-kms": "3.x",
|
package/dist/chunk-CHXZROA7.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
// src/utils/uniqueBy.ts
|
|
2
|
-
function uniqueBy(values, getKey) {
|
|
3
|
-
const map = /* @__PURE__ */ new Map();
|
|
4
|
-
for (const value of values) {
|
|
5
|
-
const key = getKey(value);
|
|
6
|
-
if (!map.has(key)) {
|
|
7
|
-
map.set(key, value);
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
return Array.from(map.values());
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export {
|
|
14
|
-
uniqueBy
|
|
15
|
-
};
|
|
16
|
-
//# sourceMappingURL=chunk-CHXZROA7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/uniqueBy.ts"],"sourcesContent":["export function uniqueBy<value, key>(values: readonly value[], getKey: (value: value) => key): readonly value[] {\n const map = new Map<key, value>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) {\n map.set(key, value);\n }\n }\n return Array.from(map.values());\n}\n"],"mappings":";AAAO,SAAS,SAAqB,QAA0B,QAAiD;AAC9G,QAAM,MAAM,oBAAI,IAAgB;AAChC,aAAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,CAAC,IAAI,IAAI,GAAG,GAAG;AACjB,UAAI,IAAI,KAAK,KAAK;AAAA,IACpB;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC;AAChC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/assertExhaustive.ts","../src/utils/bigIntMax.ts","../src/utils/bigIntMin.ts","../src/utils/bigIntSort.ts","../src/utils/chunk.ts","../src/utils/groupBy.ts","../src/utils/identity.ts","../src/utils/includes.ts","../src/utils/indent.ts","../src/utils/isDefined.ts","../src/utils/isNotNull.ts","../src/utils/iteratorToArray.ts","../src/utils/mapObject.ts","../src/utils/unique.ts","../src/utils/wait.ts","../src/utils/waitForIdle.ts"],"sourcesContent":["export function assertExhaustive(value: never, message?: string): never {\n throw new Error(message ?? `Unexpected value: ${value}`);\n}\n","export function bigIntMax(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e > m ? e : m));\n}\n","export function bigIntMin(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e < m ? e : m));\n}\n","export function bigIntSort(a: bigint, b: bigint): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","export function* chunk<T>(arr: readonly T[], n: number): Generator<readonly T[], void> {\n for (let i = 0; i < arr.length; i += n) {\n yield arr.slice(i, i + n);\n }\n}\n","export function groupBy<value, key>(\n values: readonly value[],\n getKey: (value: value) => key,\n): Map<key, readonly value[]> {\n const map = new Map<key, readonly value[]>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) map.set(key, []);\n (map.get(key) as value[]).push(value);\n }\n return map;\n}\n","export function identity<T>(value: T): T {\n return value;\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function includes<item>(items: item[], value: any): value is item {\n return items.includes(value);\n}\n","export function indent(message: string, indentation = \" \"): string {\n return message.replaceAll(/(^|\\n)/g, `$1${indentation}`);\n}\n","export function isDefined<T>(argument: T | undefined): argument is T {\n return argument !== undefined;\n}\n","export function isNotNull<T>(argument: T | null): argument is T {\n return argument !== null;\n}\n","export async function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<readonly T[]> {\n const items: T[] = [];\n for await (const item of iterator) {\n items.push(item);\n }\n return items;\n}\n","/**\n * Map each key of a source object via a given valueMap function\n */\nexport function mapObject<\n Source extends Record<string | number | symbol, unknown>,\n Target extends { [key in keyof Source]: unknown },\n>(source: Source, valueMap: (value: Source[typeof key], key: keyof Source) => Target[typeof key]): Target {\n return Object.fromEntries(\n Object.entries(source).map(([key, value]) => [key, valueMap(value as Source[keyof Source], key)]),\n ) as Target;\n}\n","export function unique<value>(values: readonly value[]): readonly value[] {\n return Array.from(new Set(values));\n}\n","export function wait(ms: number): Promise<void> {\n return new Promise<void>((resolve) => setTimeout(() => resolve(), ms));\n}\n","export function waitForIdle(): Promise<void> {\n return new Promise<void>((resolve) => {\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(() => resolve(), 1);\n }\n });\n}\n"],"mappings":";AAAO,SAAS,iBAAiB,OAAc,SAAyB;AACtE,QAAM,IAAI,MAAM,WAAW,qBAAqB,KAAK,EAAE;AACzD;;;ACFO,SAAS,aAAa,MAAwB;AACnD,SAAO,KAAK,OAAO,CAAC,GAAG,MAAO,IAAI,IAAI,IAAI,CAAE;AAC9C;;;ACFO,SAAS,aAAa,MAAwB;AACnD,SAAO,KAAK,OAAO,CAAC,GAAG,MAAO,IAAI,IAAI,IAAI,CAAE;AAC9C;;;ACFO,SAAS,WAAW,GAAW,GAAuB;AAC3D,SAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAClC;;;ACFO,UAAU,MAAS,KAAmB,GAA0C;AACrF,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;AACtC,UAAM,IAAI,MAAM,GAAG,IAAI,CAAC;AAAA,EAC1B;AACF;;;ACJO,SAAS,QACd,QACA,QAC4B;AAC5B,QAAM,MAAM,oBAAI,IAA2B;AAC3C,aAAW,SAAS,QAAQ;AAC1B,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,CAAC,IAAI,IAAI,GAAG,EAAG,KAAI,IAAI,KAAK,CAAC,CAAC;AAClC,IAAC,IAAI,IAAI,GAAG,EAAc,KAAK,KAAK;AAAA,EACtC;AACA,SAAO;AACT;;;ACXO,SAAS,SAAY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