|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { createRequire } from 'node:module'; |
| 5 | + |
| 6 | +import Web3 from 'web3'; |
| 7 | + |
| 8 | +const require = createRequire(import.meta.url); |
| 9 | +const solc = require('solc'); |
| 10 | + |
| 11 | +const DEFAULT_RPC_URL = 'http://127.0.0.1:8545'; |
| 12 | +const DEFAULT_PRIVATE_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80'; |
| 13 | + |
| 14 | +function mustReadJson(filePath) { |
| 15 | + if (!fs.existsSync(filePath)) throw new Error(`Missing file: ${filePath}`); |
| 16 | + return JSON.parse(fs.readFileSync(filePath, 'utf-8')); |
| 17 | +} |
| 18 | + |
| 19 | +function mustReadText(filePath) { |
| 20 | + if (!fs.existsSync(filePath)) throw new Error(`Missing file: ${filePath}`); |
| 21 | + return fs.readFileSync(filePath, 'utf-8'); |
| 22 | +} |
| 23 | + |
| 24 | +function compileApp(source) { |
| 25 | + const input = { |
| 26 | + language: 'Solidity', |
| 27 | + sources: { |
| 28 | + 'App.sol': { content: source } |
| 29 | + }, |
| 30 | + settings: { |
| 31 | + optimizer: { enabled: true, runs: 200 }, |
| 32 | + outputSelection: { |
| 33 | + '*': { |
| 34 | + '*': ['abi', 'evm.bytecode.object'] |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + const output = JSON.parse(solc.compile(JSON.stringify(input))); |
| 41 | + const errors = (output.errors || []).filter((e) => e.severity === 'error'); |
| 42 | + if (errors.length > 0) { |
| 43 | + throw new Error(errors.map((e) => e.formattedMessage || e.message).join('\n')); |
| 44 | + } |
| 45 | + |
| 46 | + const app = output?.contracts?.['App.sol']?.App; |
| 47 | + if (!app?.abi || !app?.evm?.bytecode?.object) { |
| 48 | + throw new Error('Failed to compile App.sol (missing abi/bytecode).'); |
| 49 | + } |
| 50 | + return { abi: app.abi, bytecode: `0x${app.evm.bytecode.object}` }; |
| 51 | +} |
| 52 | + |
| 53 | +function sampleValue(field, idx, forUpdate, accountAddress) { |
| 54 | + const suffix = `${forUpdate ? 'u' : 'c'}-${idx}`; |
| 55 | + switch (field.type) { |
| 56 | + case 'string': |
| 57 | + case 'image': |
| 58 | + return `${field.name}-${suffix}`; |
| 59 | + case 'uint256': |
| 60 | + case 'reference': |
| 61 | + case 'decimal': |
| 62 | + return String(1000 + idx); |
| 63 | + case 'int256': |
| 64 | + return String(-100 - idx); |
| 65 | + case 'bool': |
| 66 | + return idx % 2 === 0; |
| 67 | + case 'address': |
| 68 | + case 'externalReference': |
| 69 | + return accountAddress; |
| 70 | + case 'bytes32': |
| 71 | + return `0x${'ab'.repeat(32)}`; |
| 72 | + default: |
| 73 | + throw new Error(`Unsupported field type for generated tests: ${field.type}`); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +async function mustFail(promiseFactory, expectedHint) { |
| 78 | + let failed = false; |
| 79 | + try { |
| 80 | + await promiseFactory(); |
| 81 | + } catch (e) { |
| 82 | + failed = true; |
| 83 | + if (expectedHint) { |
| 84 | + const msg = String(e?.message ?? e); |
| 85 | + assert.match(msg, expectedHint, `Expected error hint ${expectedHint}, got: ${msg}`); |
| 86 | + } |
| 87 | + } |
| 88 | + assert.equal(failed, true, 'Expected operation to fail but it succeeded.'); |
| 89 | +} |
| 90 | + |
| 91 | +async function main() { |
| 92 | + const root = process.cwd(); |
| 93 | + const parent = path.resolve(root, '..'); |
| 94 | + const schemaPath = path.join(parent, 'schema.json'); |
| 95 | + const appSolPath = path.join(parent, 'contracts', 'App.sol'); |
| 96 | + |
| 97 | + const schema = mustReadJson(schemaPath); |
| 98 | + const appSol = mustReadText(appSolPath); |
| 99 | + const { abi, bytecode } = compileApp(appSol); |
| 100 | + |
| 101 | + const rpcUrl = process.env.TH_RPC_URL || DEFAULT_RPC_URL; |
| 102 | + const privateKey = process.env.TH_TEST_PRIVATE_KEY || DEFAULT_PRIVATE_KEY; |
| 103 | + const web3 = new Web3(rpcUrl); |
| 104 | + |
| 105 | + const listening = await web3.eth.net.isListening().catch(() => false); |
| 106 | + if (!listening) { |
| 107 | + throw new Error(`RPC is not reachable at ${rpcUrl}. Start anvil and retry.`); |
| 108 | + } |
| 109 | + |
| 110 | + const account = web3.eth.accounts.privateKeyToAccount(privateKey); |
| 111 | + web3.eth.accounts.wallet.add(account); |
| 112 | + web3.eth.defaultAccount = account.address; |
| 113 | + |
| 114 | + const anyPaidCreates = (schema.collections || []).some((c) => Boolean(c?.createRules?.payment)); |
| 115 | + const deployArgs = anyPaidCreates ? [account.address, account.address] : []; |
| 116 | + |
| 117 | + const app = await new web3.eth.Contract(abi) |
| 118 | + .deploy({ data: bytecode, arguments: deployArgs }) |
| 119 | + .send({ from: account.address, gas: 8_000_000 }); |
| 120 | + |
| 121 | + for (const collection of schema.collections || []) { |
| 122 | + const name = String(collection.name); |
| 123 | + const fields = Array.isArray(collection.fields) ? collection.fields : []; |
| 124 | + const mutable = Array.isArray(collection?.updateRules?.mutable) ? collection.updateRules.mutable : []; |
| 125 | + const softDelete = Boolean(collection?.deleteRules?.softDelete); |
| 126 | + const hasTransfer = Boolean(collection?.transferRules); |
| 127 | + const hasPayment = Boolean(collection?.createRules?.payment?.amountWei); |
| 128 | + const optimistic = Boolean(collection?.updateRules?.optimisticConcurrency); |
| 129 | + |
| 130 | + const createFn = `create${name}`; |
| 131 | + const listFn = `listIds${name}`; |
| 132 | + const getFn = `get${name}(uint256)`; |
| 133 | + const getWithDeletedFn = `get${name}(uint256,bool)`; |
| 134 | + const updateFn = `update${name}`; |
| 135 | + const deleteFn = `delete${name}`; |
| 136 | + const transferFn = `transfer${name}`; |
| 137 | + |
| 138 | + const createArgs = fields.map((f, idx) => sampleValue(f, idx, false, account.address)); |
| 139 | + |
| 140 | + if (hasPayment) { |
| 141 | + await mustFail(() => |
| 142 | + app.methods[createFn](...createArgs).send({ from: account.address, gas: 3_000_000 }) |
| 143 | + ); |
| 144 | + |
| 145 | + await app.methods[createFn](...createArgs).send({ |
| 146 | + from: account.address, |
| 147 | + gas: 3_000_000, |
| 148 | + value: String(collection.createRules.payment.amountWei) |
| 149 | + }); |
| 150 | + } else { |
| 151 | + await app.methods[createFn](...createArgs).send({ from: account.address, gas: 3_000_000 }); |
| 152 | + } |
| 153 | + |
| 154 | + const ids = await app.methods[listFn](0, 20, false).call(); |
| 155 | + assert.equal(Array.isArray(ids), true, `${listFn} must return an array`); |
| 156 | + assert.equal(ids.length > 0, true, `${listFn} must include created record`); |
| 157 | + const id = Number(ids[0]); |
| 158 | + |
| 159 | + const current = await app.methods[getFn](id).call(); |
| 160 | + assert.ok(current, `${getFn} should return a record`); |
| 161 | + |
| 162 | + if (hasTransfer) { |
| 163 | + const accounts = await web3.eth.getAccounts(); |
| 164 | + const to = accounts[1] || account.address; |
| 165 | + await app.methods[transferFn](id, to).send({ from: account.address, gas: 3_000_000 }); |
| 166 | + const afterTransfer = await app.methods[getFn](id).call(); |
| 167 | + assert.equal( |
| 168 | + String(afterTransfer.owner || '').toLowerCase(), |
| 169 | + String(to).toLowerCase(), |
| 170 | + `${transferFn} should update owner` |
| 171 | + ); |
| 172 | + } |
| 173 | + |
| 174 | + if (mutable.length > 0) { |
| 175 | + const updateArgs = [id]; |
| 176 | + for (const mutableFieldName of mutable) { |
| 177 | + const field = fields.find((f) => f?.name === mutableFieldName); |
| 178 | + if (!field) continue; |
| 179 | + updateArgs.push(sampleValue(field, 777, true, account.address)); |
| 180 | + } |
| 181 | + if (optimistic) updateArgs.push('0'); |
| 182 | + |
| 183 | + await app.methods[updateFn](...updateArgs).send({ from: account.address, gas: 3_000_000 }); |
| 184 | + const afterUpdate = await app.methods[getFn](id).call(); |
| 185 | + const firstMutable = mutable[0]; |
| 186 | + const firstMutableField = fields.find((f) => f.name === firstMutable); |
| 187 | + if (firstMutable && firstMutable in afterUpdate && firstMutableField) { |
| 188 | + assert.equal( |
| 189 | + String(afterUpdate[firstMutable]), |
| 190 | + String(sampleValue(firstMutableField, 777, true, account.address)), |
| 191 | + `${updateFn} should update mutable field ${firstMutable}` |
| 192 | + ); |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + if (softDelete) { |
| 197 | + await app.methods[deleteFn](id).send({ from: account.address, gas: 3_000_000 }); |
| 198 | + const deletedRecord = await app.methods[getWithDeletedFn](id, true).call(); |
| 199 | + assert.equal(Boolean(deletedRecord.isDeleted), true, `${deleteFn} should mark isDeleted`); |
| 200 | + |
| 201 | + const activeIds = await app.methods[listFn](0, 20, false).call(); |
| 202 | + const hasId = (activeIds || []).map((x) => String(x)).includes(String(id)); |
| 203 | + assert.equal(hasId, false, `${listFn} should exclude soft-deleted record by default`); |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + console.log('PASS contract integration scaffold'); |
| 208 | +} |
| 209 | + |
| 210 | +main().catch((e) => { |
| 211 | + console.error(String(e?.stack || e?.message || e)); |
| 212 | + process.exit(1); |
| 213 | +}); |
0 commit comments