-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcontracts.test.ts
More file actions
258 lines (216 loc) · 10.5 KB
/
Copy pathcontracts.test.ts
File metadata and controls
258 lines (216 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Buffer } from "node:buffer";
import { extractFoundryBytecode, extractHardhatBytecode, hexToBytes } from "./contracts.js";
// ── skipBuild mocks ──────────────────────────────────────────────────────────
//
// These mocks exist purely for the skipBuild integration tests at the bottom of
// this file. The pure-helper tests above do not need them.
const { runStreamedMock, deployBatchMock } = vi.hoisted(() => ({
runStreamedMock: vi.fn(async () => {}),
deployBatchMock: vi.fn(async () => ({
addresses: ["0xdeadbeef"] as `0x${string}`[],
chunkCount: 1,
})),
}));
vi.mock("../process.js", () => ({
runStreamed: runStreamedMock,
}));
vi.mock("@dotdm/contracts", async (importOriginal) => {
const real = await importOriginal<typeof import("@dotdm/contracts")>();
return {
...real,
buildContracts: vi.fn(async () => ({
contracts: [{ crate: "flipper", pvmPath: "/tmp/flipper.polkavm" }],
totalDurationMs: 1,
})),
detectContracts: vi.fn(() => [{ name: "flipper" }]),
ContractDeployer: class MockContractDeployer {
deployBatch = deployBatchMock;
},
};
});
describe("hexToBytes", () => {
it("decodes a 0x-prefixed hex string", () => {
expect(hexToBytes("0x50564d00")).toEqual(new Uint8Array([0x50, 0x56, 0x4d, 0x00]));
});
it("decodes a bare hex string without the 0x prefix", () => {
expect(hexToBytes("deadbeef")).toEqual(new Uint8Array([0xde, 0xad, 0xbe, 0xef]));
});
it("treats an empty '0x' as a zero-length byte array", () => {
// Abstract Solidity contracts compile to bytecode "0x"; the caller
// uses length === 0 as the skip signal, so decoding must succeed.
const out = hexToBytes("0x");
expect(out).toBeInstanceOf(Uint8Array);
expect(out.length).toBe(0);
});
it("treats a completely empty string as a zero-length byte array", () => {
const out = hexToBytes("");
expect(out).toBeInstanceOf(Uint8Array);
expect(out.length).toBe(0);
});
it("throws a clear error on odd-length input", () => {
expect(() => hexToBytes("0xabc")).toThrow(/invalid hex string \(odd length\)/);
expect(() => hexToBytes("abc")).toThrow(/invalid hex string \(odd length\)/);
});
it("round-trips random byte sequences via Buffer.toString('hex')", () => {
// Spot-check against Node's Buffer implementation to guard against
// off-by-one bugs in the slice/parseInt loop.
const samples: Uint8Array[] = [
new Uint8Array([0]),
new Uint8Array([0xff]),
new Uint8Array([0x00, 0x01, 0x02, 0x03, 0xfe, 0xff]),
new Uint8Array(Array.from({ length: 64 }, (_, i) => (i * 31) & 0xff)),
new Uint8Array(Array.from({ length: 257 }, (_, i) => i & 0xff)),
];
for (const bytes of samples) {
const hex = `0x${Buffer.from(bytes).toString("hex")}`;
expect(hexToBytes(hex)).toEqual(bytes);
// No-prefix variant should match too.
expect(hexToBytes(hex.slice(2))).toEqual(bytes);
}
});
});
describe("extractFoundryBytecode", () => {
it("returns the hex under bytecode.object for a well-formed artifact", () => {
expect(extractFoundryBytecode({ bytecode: { object: "0x60806040" } })).toBe("0x60806040");
});
it("returns null for an empty '0x' placeholder", () => {
// forge emits "0x" for interfaces / abstract contracts; we must skip,
// not attempt to deploy a zero-byte blob.
expect(extractFoundryBytecode({ bytecode: { object: "0x" } })).toBeNull();
});
it("returns null when bytecode.object is missing", () => {
expect(extractFoundryBytecode({ bytecode: {} })).toBeNull();
});
it("returns null when the top-level bytecode field is missing", () => {
expect(extractFoundryBytecode({})).toBeNull();
});
it("returns null for non-object inputs", () => {
// JSON.parse can legitimately produce these for junk files we'd
// rather skip than crash on.
expect(extractFoundryBytecode(null)).toBeNull();
expect(extractFoundryBytecode(undefined)).toBeNull();
expect(extractFoundryBytecode("0x60806040")).toBeNull();
expect(extractFoundryBytecode(42)).toBeNull();
});
it("returns null when bytecode.object is not a string", () => {
expect(extractFoundryBytecode({ bytecode: { object: 42 } })).toBeNull();
expect(extractFoundryBytecode({ bytecode: { object: null } })).toBeNull();
});
});
describe("extractHardhatBytecode", () => {
it("returns the plain-string bytecode field", () => {
expect(extractHardhatBytecode({ bytecode: "0x60806040" })).toBe("0x60806040");
});
it("returns null for an empty '0x' placeholder", () => {
expect(extractHardhatBytecode({ bytecode: "0x" })).toBeNull();
});
it("returns null when the bytecode field is missing", () => {
expect(extractHardhatBytecode({})).toBeNull();
});
it("refuses the Foundry { object } shape", () => {
// Hardhat artifacts store bytecode as a plain string. A misrouted
// artifact with the Foundry nested shape should fail loudly (null →
// skip) rather than silently feed the wrong bytes into a deploy.
expect(extractHardhatBytecode({ bytecode: { object: "0x60806040" } })).toBeNull();
});
it("returns null for non-object inputs", () => {
expect(extractHardhatBytecode(null)).toBeNull();
expect(extractHardhatBytecode(undefined)).toBeNull();
expect(extractHardhatBytecode("0x60806040")).toBeNull();
expect(extractHardhatBytecode(42)).toBeNull();
});
});
// ── skipBuild integration tests ───────────────────────────────────────────────
//
// These tests verify that the compile step (runStreamed) is NOT called when
// skipBuild is true, and that the discovery loop reads pre-existing artifacts.
// They use a real tmp dir so the fs checks in compileFoundry/compileHardhat
// work correctly; ContractDeployer.deployBatch is mocked to avoid chain I/O.
import { runContractsPhase } from "./contracts.js";
function makeOpts(projectDir: string, contractsType: "foundry" | "hardhat", skipBuild: boolean) {
return {
projectDir,
contractsType,
skipBuild,
// ContractDeployer is mocked — provide the minimal shape that the
// constructor call `new ContractDeployer(signer, origin, raw.assetHub,
// assetHub)` accesses before handing off to the mock.
client: { raw: { assetHub: {} }, assetHub: {} } as any,
signer: {} as any,
origin: "5FakeAddress" as any,
onEvent: () => {},
};
}
describe("runContractsPhase skipBuild=true (foundry)", () => {
let dir: string;
beforeEach(() => {
runStreamedMock.mockClear();
deployBatchMock.mockClear();
// Fresh tmp dir per test so artifact presence/absence is controlled.
dir = mkdtempSync(join(tmpdir(), "contracts-test-foundry-"));
});
it("uses existing foundry artifacts without spawning forge", async () => {
// Set up out/Counter.sol/Counter.json with real bytecode.
const solDir = join(dir, "out", "Counter.sol");
mkdirSync(solDir, { recursive: true });
writeFileSync(
join(solDir, "Counter.json"),
JSON.stringify({ bytecode: { object: "0x6080604052" } }),
);
const result = await runContractsPhase(makeOpts(dir, "foundry", true));
expect(runStreamedMock).not.toHaveBeenCalled();
expect(result.deployed).toHaveLength(1);
expect(result.deployed[0].name).toBe("Counter");
});
it("throws with a clear message when out/ is missing", async () => {
// No out/ directory — simulates a project where forge was never run.
mkdirSync(dir, { recursive: true });
await expect(runContractsPhase(makeOpts(dir, "foundry", true))).rejects.toThrow(
/no pre-built contract artifacts found at/,
);
expect(runStreamedMock).not.toHaveBeenCalled();
});
it("throws with a clear message when out/ exists but has no valid artifacts", async () => {
// out/ exists but is empty — forge ran but produced nothing usable.
mkdirSync(join(dir, "out"), { recursive: true });
await expect(runContractsPhase(makeOpts(dir, "foundry", true))).rejects.toThrow(
/no pre-built contract artifacts found at/,
);
});
});
describe("runContractsPhase skipBuild=true (hardhat)", () => {
let dir: string;
beforeEach(() => {
runStreamedMock.mockClear();
deployBatchMock.mockClear();
dir = mkdtempSync(join(tmpdir(), "contracts-test-hardhat-"));
});
it("uses existing hardhat artifacts without spawning npx hardhat compile", async () => {
// Set up artifacts/contracts/Lock.sol/Lock.json with real bytecode.
const solDir = join(dir, "artifacts", "contracts", "Lock.sol");
mkdirSync(solDir, { recursive: true });
writeFileSync(join(solDir, "Lock.json"), JSON.stringify({ bytecode: "0x6080604052" }));
const result = await runContractsPhase(makeOpts(dir, "hardhat", true));
expect(runStreamedMock).not.toHaveBeenCalled();
expect(result.deployed).toHaveLength(1);
expect(result.deployed[0].name).toBe("Lock");
});
it("throws with a clear message when artifacts/contracts/ is missing", async () => {
mkdirSync(dir, { recursive: true });
await expect(runContractsPhase(makeOpts(dir, "hardhat", true))).rejects.toThrow(
/no pre-built contract artifacts found at/,
);
expect(runStreamedMock).not.toHaveBeenCalled();
});
it("throws with a clear message when artifacts/contracts/ has no valid artifacts", async () => {
// Directory exists but contains no .sol subdirs with valid JSON.
mkdirSync(join(dir, "artifacts", "contracts"), { recursive: true });
await expect(runContractsPhase(makeOpts(dir, "hardhat", true))).rejects.toThrow(
/no pre-built contract artifacts found at/,
);
});
});