@umacloud/knowledge 1.0.1

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.
Files changed (418) hide show
  1. package/00-governance/governance-capabilities.md +557 -0
  2. package/00-governance/knowledge-map.md +39 -0
  3. package/00-governance/maintenance-policy.md +76 -0
  4. package/00-governance/review-checklist.md +81 -0
  5. package/README.md +13 -0
  6. package/ai/01-standards/agent-development-complete.md +691 -0
  7. package/ai/01-standards/llm-application-complete.md +488 -0
  8. package/ai/01-standards/mlops-complete.md +798 -0
  9. package/ai/01-standards/prompt-engineering-complete.md +646 -0
  10. package/ai/01-standards/rag-architecture-complete.md +649 -0
  11. package/ai/02-playbooks/llm-evaluation-playbook.md +847 -0
  12. package/ai/03-checklists/ai-project-checklist.md +215 -0
  13. package/ai/04-antipatterns/ai-antipatterns.md +661 -0
  14. package/ai/05-cases/case-rag-production.md +147 -0
  15. package/ai/06-glossary/ai-glossary.md +162 -0
  16. package/ai/agent-evaluation-benchmark.md +53 -0
  17. package/ai/ai-agent-memory-context-management.md +41 -0
  18. package/ai/ai-cost-capacity-optimization-playbook.md +42 -0
  19. package/ai/ai-data-security-and-compliance-playbook.md +37 -0
  20. package/ai/ai-domain-index-and-checklist.md +40 -0
  21. package/ai/ai-governance-maturity-model.md +50 -0
  22. package/ai/ai-model-selection-and-routing-strategy.md +47 -0
  23. package/ai/ai-observability-and-oncall-runbook.md +52 -0
  24. package/ai/ai-rag-engineering-playbook.md +42 -0
  25. package/ai/ai-red-team-and-safety-evaluation.md +42 -0
  26. package/ai/ai-release-readiness-and-rollback-gate.md +42 -0
  27. package/ai/llm-agent-engineering-deep-dive.md +57 -0
  28. package/ai/prompt-and-tool-guardrails.md +52 -0
  29. package/api/01-standards/enterprise-api-standards.md +198 -0
  30. package/api/01-standards/rest-api-design-guide.md +63 -0
  31. package/api/02-playbooks/api-pagination-playbook.md +93 -0
  32. package/api/02-playbooks/graphql-production-playbook.md +176 -0
  33. package/api/03-checklists/api-review-checklist.md +55 -0
  34. package/api/04-antipatterns/api-antipatterns.md +112 -0
  35. package/architecture/01-standards/api-gateway-patterns.md +496 -0
  36. package/architecture/01-standards/cloud-native-patterns.md +644 -0
  37. package/architecture/01-standards/distributed-systems-patterns.md +591 -0
  38. package/architecture/01-standards/event-driven-architecture.md +595 -0
  39. package/architecture/01-standards/microservices-patterns-complete.md +968 -0
  40. package/architecture/01-standards/microservices-patterns.md +495 -0
  41. package/architecture/01-standards/system-design-interview.md +664 -0
  42. package/architecture/02-playbooks/microservices-patterns-playbook.md +137 -0
  43. package/architecture/02-playbooks/migration-playbook.md +780 -0
  44. package/architecture/02-playbooks/system-design-playbook.md +779 -0
  45. package/architecture/03-checklists/architecture-decision-checklist.md +297 -0
  46. package/architecture/04-antipatterns/architecture-antipatterns.md +417 -0
  47. package/architecture/05-cases/case-netflix-microservices.md +413 -0
  48. package/architecture/06-glossary/architecture-glossary.md +164 -0
  49. package/architecture/adr-template-and-examples.md +38 -0
  50. package/architecture/api-gateway-deep-dive.md +1291 -0
  51. package/architecture/configuration-management.md +1162 -0
  52. package/architecture/distributed-transactions.md +1220 -0
  53. package/architecture/microservices-complete.md +735 -0
  54. package/architecture/resilience-and-disaster-patterns.md +37 -0
  55. package/architecture/service-governance.md +1198 -0
  56. package/architecture/system-architecture-deep-dive.md +37 -0
  57. package/backend/01-standards/analytics-and-growth.md +65 -0
  58. package/backend/01-standards/api-and-error-conventions.md +120 -0
  59. package/backend/01-standards/application-layering-and-packaging.md +160 -0
  60. package/backend/01-standards/auth-implementation.md +104 -0
  61. package/backend/01-standards/backend-framework-idioms.md +74 -0
  62. package/backend/01-standards/background-jobs-and-async.md +66 -0
  63. package/backend/01-standards/caching-strategies-complete.md +390 -0
  64. package/backend/01-standards/config-and-observability.md +77 -0
  65. package/backend/01-standards/data-modeling-and-persistence.md +94 -0
  66. package/backend/01-standards/django-complete.md +1765 -0
  67. package/backend/01-standards/email-and-notifications.md +64 -0
  68. package/backend/01-standards/fastapi-complete.md +925 -0
  69. package/backend/01-standards/file-upload-and-storage.md +66 -0
  70. package/backend/01-standards/graphql-api-complete.md +416 -0
  71. package/backend/01-standards/llm-application-standard.md +78 -0
  72. package/backend/01-standards/message-queue-patterns.md +379 -0
  73. package/backend/01-standards/microservices-and-distributed.md +78 -0
  74. package/backend/01-standards/nestjs-complete.md +2167 -0
  75. package/backend/01-standards/payment-integration.md +80 -0
  76. package/backend/01-standards/rate-limiting-complete.md +451 -0
  77. package/backend/01-standards/realtime-and-websocket.md +65 -0
  78. package/backend/01-standards/search-and-filtering.md +64 -0
  79. package/backend/01-standards/spring-boot-complete.md +445 -0
  80. package/backend/02-playbooks/api-design-playbook.md +718 -0
  81. package/backend/02-playbooks/email-send-playbook.md +130 -0
  82. package/backend/02-playbooks/file-upload-s3-playbook.md +153 -0
  83. package/backend/02-playbooks/typescript-enterprise-playbook.md +133 -0
  84. package/backend/02-playbooks/websocket-realtime-playbook.md +154 -0
  85. package/backend/03-checklists/api-launch-checklist.md +189 -0
  86. package/backend/04-antipatterns/backend-antipatterns.md +1051 -0
  87. package/blockchain/01-standards/blockchain-basics.md +557 -0
  88. package/blockchain/01-standards/smart-contract-development.md +1315 -0
  89. package/cicd/01-standards/deployment-and-delivery-standard.md +96 -0
  90. package/cicd/01-standards/github-actions-complete.md +473 -0
  91. package/cicd/01-standards/release-and-store-submission.md +75 -0
  92. package/cicd/02-playbooks/cicd-pipeline-playbook.md +144 -0
  93. package/cicd/02-playbooks/release-management-playbook.md +605 -0
  94. package/cicd/03-checklists/pipeline-security-checklist.md +168 -0
  95. package/cicd/04-antipatterns/cicd-antipatterns.md +589 -0
  96. package/cicd/05-cases/case-deployment-automation.md +221 -0
  97. package/cicd/05-cases/case-gitops-transformation.md +212 -0
  98. package/cicd/06-glossary/cicd-glossary.md +114 -0
  99. package/cicd/cicd-blueprint-deep-dive.md +38 -0
  100. package/cicd/release-readiness-gate.md +37 -0
  101. package/cloud-native/01-standards/container-security.md +741 -0
  102. package/cloud-native/01-standards/kubernetes-complete.md +812 -0
  103. package/cloud-native/02-playbooks/api-gateway-playbook.md +155 -0
  104. package/cloud-native/02-playbooks/gitops-with-argocd.md +760 -0
  105. package/cloud-native/02-playbooks/k8s-troubleshooting-playbook.md +1942 -0
  106. package/cloud-native/02-playbooks/message-queue-playbook.md +129 -0
  107. package/cloud-native/02-playbooks/multicloud-governance.md +726 -0
  108. package/cloud-native/02-playbooks/serverless-patterns.md +788 -0
  109. package/cloud-native/02-playbooks/service-mesh-playbook.md +612 -0
  110. package/cloud-native/02-playbooks/terraform-iac-playbook.md +143 -0
  111. package/cloud-native/03-checklists/container-security-checklist.md +431 -0
  112. package/cloud-native/03-checklists/k8s-production-readiness-checklist.md +460 -0
  113. package/cloud-native/04-antipatterns/container-antipatterns.md +660 -0
  114. package/cloud-native/04-antipatterns/k8s-antipatterns.md +743 -0
  115. package/cloud-native/05-cases/case-k8s-migration.md +478 -0
  116. package/cloud-native/05-cases/case-k8s-scaling.md +642 -0
  117. package/cloud-native/05-cases/case-k8s-security-incident.md +397 -0
  118. package/cloud-native/06-glossary/cloud-native-glossary.md +337 -0
  119. package/cross-platform/01-standards/cross-platform-frameworks.md +83 -0
  120. package/cross-platform/01-standards/platform-selection-and-architecture.md +77 -0
  121. package/data/01-standards/elasticsearch-complete.md +2098 -0
  122. package/data/01-standards/postgresql-complete.md +1613 -0
  123. package/data/01-standards/redis-complete.md +1527 -0
  124. package/data/02-playbooks/database-optimization-playbook.md +403 -0
  125. package/data/02-playbooks/elasticsearch-production-playbook.md +132 -0
  126. package/data/03-checklists/database-launch-checklist.md +187 -0
  127. package/data/04-antipatterns/database-antipatterns.md +873 -0
  128. package/data/05-cases/case-database-migration.md +310 -0
  129. package/data/06-glossary/database-glossary.md +440 -0
  130. package/data/data-governance-and-modeling-deep-dive.md +39 -0
  131. package/data-engineering/01-standards/airflow-complete.md +523 -0
  132. package/data-engineering/01-standards/kafka-complete.md +1521 -0
  133. package/data-engineering/02-playbooks/spark-etl-playbook.md +496 -0
  134. package/data-engineering/03-checklists/pipeline-launch-checklist.md +194 -0
  135. package/data-engineering/04-antipatterns/data-pipeline-antipatterns.md +684 -0
  136. package/data-engineering/05-cases/case-real-time-pipeline.md +355 -0
  137. package/data-engineering/06-glossary/data-engineering-glossary.md +429 -0
  138. package/database/01-standards/database-schema-standards.md +147 -0
  139. package/database/02-playbooks/postgresql-optimization-quick.md +52 -0
  140. package/database/02-playbooks/postgresql-performance-optimization.md +58 -0
  141. package/database/02-playbooks/postgresql-production-playbook.md +146 -0
  142. package/database/02-playbooks/redis-caching-playbook.md +117 -0
  143. package/database/03-checklists/database-review-checklist.md +50 -0
  144. package/database/04-antipatterns/database-antipatterns.md +112 -0
  145. package/design/01-standards/ui-design-system-complete.md +423 -0
  146. package/design/02-playbooks/design-handoff-playbook.md +254 -0
  147. package/design/02-playbooks/design-review-playbook.md +388 -0
  148. package/design/03-checklists/design-review-checklist.md +246 -0
  149. package/design/04-antipatterns/design-antipatterns.md +378 -0
  150. package/design/05-cases/case-design-system-adoption.md +328 -0
  151. package/design/06-glossary/design-glossary.md +329 -0
  152. package/design/ui-full-lifecycle-cross-platform-playbook.md +571 -0
  153. package/design/ux-system-deep-dive.md +38 -0
  154. package/design-systems/00-craft-rules.md +71 -0
  155. package/design-systems/aesthetic-families.md +43 -0
  156. package/design-systems/anti-ai-slop.md +162 -0
  157. package/design-systems/bold-geometric.md +120 -0
  158. package/design-systems/brutalist-bold.md +103 -0
  159. package/design-systems/editorial-clean.md +109 -0
  160. package/design-systems/glass-aurora.md +108 -0
  161. package/design-systems/modern-minimal.md +145 -0
  162. package/design-systems/premium-luxury.md +106 -0
  163. package/design-systems/product-type-design-map.md +48 -0
  164. package/design-systems/soft-warm.md +123 -0
  165. package/design-systems/tech-utility.md +113 -0
  166. package/desktop/01-standards/desktop-app-standard.md +72 -0
  167. package/desktop/01-standards/desktop-design.md +71 -0
  168. package/development/00-governance/document-template.md +41 -0
  169. package/development/01-standards/api-versioning-strategies.md +432 -0
  170. package/development/01-standards/authentication-patterns-complete.md +479 -0
  171. package/development/01-standards/css-architecture-complete.md +550 -0
  172. package/development/01-standards/database-migration-strategies.md +484 -0
  173. package/development/01-standards/elasticsearch-complete.md +347 -0
  174. package/development/01-standards/git-complete.md +371 -0
  175. package/development/01-standards/golang-complete.md +1565 -0
  176. package/development/01-standards/graphql-complete.md +298 -0
  177. package/development/01-standards/javascript-bundlers-complete.md +469 -0
  178. package/development/01-standards/javascript-typescript-complete.md +528 -0
  179. package/development/01-standards/jest-complete.md +275 -0
  180. package/development/01-standards/linux-complete.md +234 -0
  181. package/development/01-standards/logging-observability-complete.md +526 -0
  182. package/development/01-standards/microservices-communication.md +502 -0
  183. package/development/01-standards/mongodb-complete.md +406 -0
  184. package/development/01-standards/oauth2-complete.md +285 -0
  185. package/development/01-standards/performance-optimization-complete.md +289 -0
  186. package/development/01-standards/playwright-complete.md +247 -0
  187. package/development/01-standards/postgresql-complete.md +456 -0
  188. package/development/01-standards/pytest-complete.md +340 -0
  189. package/development/01-standards/python-async-programming.md +902 -0
  190. package/development/01-standards/python-complete.md +956 -0
  191. package/development/01-standards/python-decorators-complete.md +799 -0
  192. package/development/01-standards/python-design-patterns.md +2854 -0
  193. package/development/01-standards/python-packaging-distribution.md +420 -0
  194. package/development/01-standards/python-testing-strategies.md +607 -0
  195. package/development/01-standards/python-web-frameworks-comparison.md +471 -0
  196. package/development/01-standards/redis-complete.md +317 -0
  197. package/development/01-standards/rest-api-complete.md +316 -0
  198. package/development/01-standards/rust-complete.md +578 -0
  199. package/development/01-standards/typescript-advanced-types.md +1513 -0
  200. package/development/01-standards/web-security-complete.md +292 -0
  201. package/development/02-playbooks/api-design-playbook.md +810 -0
  202. package/development/02-playbooks/database-migration-playbook.md +580 -0
  203. package/development/02-playbooks/debugging-playbook.md +692 -0
  204. package/development/02-playbooks/feature-delivery-playbook.md +430 -0
  205. package/development/02-playbooks/incident-hotfix-playbook.md +387 -0
  206. package/development/02-playbooks/performance-optimization-playbook.md +531 -0
  207. package/development/02-playbooks/performance-tuning-playbook.md +652 -0
  208. package/development/02-playbooks/refactor-playbook.md +403 -0
  209. package/development/02-playbooks/release-playbook.md +469 -0
  210. package/development/03-checklists/architecture-review-checklist.md +168 -0
  211. package/development/03-checklists/data-migration-checklist.md +157 -0
  212. package/development/03-checklists/oncall-handover-checklist.md +173 -0
  213. package/development/03-checklists/pr-checklist.md +158 -0
  214. package/development/03-checklists/production-readiness-checklist.md +190 -0
  215. package/development/03-checklists/release-readiness-checklist.md +154 -0
  216. package/development/03-checklists/security-review-checklist.md +182 -0
  217. package/development/04-antipatterns/api-antipatterns.md +657 -0
  218. package/development/04-antipatterns/architecture-antipatterns.md +686 -0
  219. package/development/04-antipatterns/backend-antipatterns.md +648 -0
  220. package/development/04-antipatterns/cicd-antipatterns.md +540 -0
  221. package/development/04-antipatterns/code-smell-antipatterns.md +571 -0
  222. package/development/04-antipatterns/data-antipatterns.md +658 -0
  223. package/development/04-antipatterns/database-antipatterns.md +578 -0
  224. package/development/04-antipatterns/frontend-antipatterns.md +635 -0
  225. package/development/04-antipatterns/reliability-antipatterns.md +700 -0
  226. package/development/04-antipatterns/security-antipatterns.md +747 -0
  227. package/development/05-cases/case-api-version-migration.md +428 -0
  228. package/development/05-cases/case-authorization-hardening.md +383 -0
  229. package/development/05-cases/case-bluegreen-rollback.md +466 -0
  230. package/development/05-cases/case-cache-snowball-protection.md +485 -0
  231. package/development/05-cases/case-ci-cd-pipeline.md +544 -0
  232. package/development/05-cases/case-database-scaling.md +500 -0
  233. package/development/05-cases/case-db-hotspot-optimization.md +487 -0
  234. package/development/05-cases/case-incident-mttr-reduction.md +563 -0
  235. package/development/05-cases/case-microservice-migration.md +375 -0
  236. package/development/05-cases/case-performance-optimization.md +406 -0
  237. package/development/05-cases/case-security-incident-response.md +345 -0
  238. package/development/06-glossary/full-stack-glossary.md +166 -0
  239. package/development/09-maturity/quarterly-audit-template.md +35 -0
  240. package/development/11-ui-excellence/ui-aesthetic-system.md +41 -0
  241. package/development/11-ui-excellence/ui-engineering-excellence.md +435 -0
  242. package/development/12-scenarios/development-scenarios-guide.md +565 -0
  243. package/development/13-implementation-assets/implementation-toolkit.md +282 -0
  244. package/development/13-implementation-assets/knowledge-gates-execution.md +43 -0
  245. package/development/14-full-lifecycle/software-lifecycle-gates.md +511 -0
  246. package/development/15-lifecycle-templates/project-templates-collection.md +791 -0
  247. package/development/api-contract-and-versioning-guide.md +36 -0
  248. package/development/api-governance-complete.md +43 -0
  249. package/development/backend-engineering-complete.md +43 -0
  250. package/development/code-review-quality-complete.md +43 -0
  251. package/development/concurrency-reliability-complete.md +43 -0
  252. package/development/database-engineering-complete.md +43 -0
  253. package/development/engineering-effectiveness-complete.md +43 -0
  254. package/development/engineering-standards-deep-dive.md +38 -0
  255. package/development/frontend-engineering-complete.md +43 -0
  256. package/development/performance-capacity-complete.md +43 -0
  257. package/development/refactor-migration-complete.md +42 -0
  258. package/development/refactoring-and-techdebt-playbook.md +37 -0
  259. package/development/security-in-development-complete.md +43 -0
  260. package/devops/01-standards/cicd-pipeline-complete.md +262 -0
  261. package/devops/01-standards/docker-complete.md +1490 -0
  262. package/devops/01-standards/github-actions-complete.md +337 -0
  263. package/devops/01-standards/kubernetes-complete.md +638 -0
  264. package/devops/01-standards/terraform-complete.md +2117 -0
  265. package/devops/02-playbooks/docker-compose-playbook.md +233 -0
  266. package/devops/02-playbooks/docker-k8s-production-playbook.md +186 -0
  267. package/devops/02-playbooks/docker-production-playbook.md +952 -0
  268. package/edge-iot/01-standards/edge-iot-complete.md +473 -0
  269. package/experts/architect/api-design.md +178 -0
  270. package/experts/architect/methodology.md +124 -0
  271. package/experts/architect/security.md +75 -0
  272. package/experts/backend-lead/methodology.md +216 -0
  273. package/experts/devops/methodology.md +160 -0
  274. package/experts/frontend-lead/methodology.md +178 -0
  275. package/experts/product-manager/industry/ecommerce.md +43 -0
  276. package/experts/product-manager/industry/saas.md +40 -0
  277. package/experts/product-manager/methodology.md +97 -0
  278. package/experts/qa-lead/methodology.md +123 -0
  279. package/experts/qa-lead/test-strategy.md +128 -0
  280. package/experts/uiux-designer/methodology.md +125 -0
  281. package/frontend/01-standards/accessibility-complete.md +532 -0
  282. package/frontend/01-standards/accessibility-standard.md +74 -0
  283. package/frontend/01-standards/admin-dashboard-and-crud.md +72 -0
  284. package/frontend/01-standards/design-tokens-complete.md +444 -0
  285. package/frontend/01-standards/forms-and-validation.md +77 -0
  286. package/frontend/01-standards/frontend-architecture-and-layering.md +119 -0
  287. package/frontend/01-standards/i18n-and-localization.md +65 -0
  288. package/frontend/01-standards/nextjs-complete.md +451 -0
  289. package/frontend/01-standards/react-complete.md +713 -0
  290. package/frontend/01-standards/react-hooks-complete-guide.md +1100 -0
  291. package/frontend/01-standards/react-hooks-complete.md +1171 -0
  292. package/frontend/01-standards/seo-and-web-vitals.md +77 -0
  293. package/frontend/01-standards/state-management-complete.md +444 -0
  294. package/frontend/01-standards/vue-complete.md +499 -0
  295. package/frontend/01-standards/vue3-complete.md +2002 -0
  296. package/frontend/01-standards/web-framework-best-practices.md +64 -0
  297. package/frontend/01-standards/web-performance-complete.md +495 -0
  298. package/frontend/02-playbooks/accessibility-a11y-playbook.md +161 -0
  299. package/frontend/02-playbooks/frontend-performance-playbook.md +707 -0
  300. package/frontend/02-playbooks/i18n-internationalization-playbook.md +120 -0
  301. package/frontend/02-playbooks/performance-optimization-playbook.md +163 -0
  302. package/frontend/02-playbooks/react-nextjs-production-playbook.md +167 -0
  303. package/frontend/02-playbooks/react-state-management-playbook.md +173 -0
  304. package/frontend/03-checklists/component-quality-checklist.md +166 -0
  305. package/frontend/03-checklists/frontend-launch-checklist.md +299 -0
  306. package/frontend/04-antipatterns/frontend-antipatterns.md +886 -0
  307. package/frontend/05-cases/case-performance-optimization.md +274 -0
  308. package/harmony/01-standards/harmonyos-arkts-standard.md +75 -0
  309. package/harmony/01-standards/harmonyos-design.md +65 -0
  310. package/high-quality-engineering-playbook.md +54 -0
  311. package/incident/01-standards/incident-response-complete.md +303 -0
  312. package/incident/02-playbooks/chaos-engineering-playbook.md +883 -0
  313. package/incident/02-playbooks/postmortem-playbook.md +398 -0
  314. package/incident/03-checklists/incident-readiness-checklist.md +181 -0
  315. package/incident/04-antipatterns/incident-antipatterns.md +490 -0
  316. package/incident/05-cases/case-cascade-failure.md +176 -0
  317. package/incident/06-glossary/incident-glossary.md +114 -0
  318. package/incident/postmortem-and-response-deep-dive.md +39 -0
  319. package/industries/ecommerce/ecommerce-complete.md +631 -0
  320. package/industries/education/education-complete.md +555 -0
  321. package/industries/fintech/fintech-complete.md +501 -0
  322. package/industries/gaming/gaming-complete.md +587 -0
  323. package/industries/healthcare/healthcare-complete.md +452 -0
  324. package/low-code/01-standards/low-code-complete.md +944 -0
  325. package/miniprogram/01-standards/ai-common-mistakes.md +61 -0
  326. package/miniprogram/01-standards/miniprogram-custom-navbar-capsule.md +77 -0
  327. package/miniprogram/01-standards/miniprogram-design.md +61 -0
  328. package/miniprogram/01-standards/miniprogram-standard.md +81 -0
  329. package/mobile/01-standards/android-material-design.md +70 -0
  330. package/mobile/01-standards/flutter-complete.md +384 -0
  331. package/mobile/01-standards/ios-design-hig.md +78 -0
  332. package/mobile/01-standards/mobile-app-standard.md +85 -0
  333. package/mobile/01-standards/react-native-complete.md +352 -0
  334. package/mobile/02-playbooks/mobile-cross-platform-playbook.md +175 -0
  335. package/mobile/02-playbooks/mobile-performance.md +473 -0
  336. package/mobile/03-checklists/mobile-release-checklist.md +234 -0
  337. package/mobile/04-antipatterns/mobile-antipatterns.md +798 -0
  338. package/mobile/05-cases/case-app-performance.md +500 -0
  339. package/mobile/05-cases/case-app-startup-optimization.md +218 -0
  340. package/mobile/06-glossary/mobile-glossary.md +484 -0
  341. package/observability/01-standards/observability-standards.md +103 -0
  342. package/observability/02-playbooks/prometheus-grafana-playbook.md +135 -0
  343. package/observability/02-playbooks/structured-logging-playbook.md +73 -0
  344. package/observability/03-checklists/observability-checklist.md +54 -0
  345. package/observability/04-antipatterns/observability-antipatterns.md +106 -0
  346. package/operations/01-standards/prometheus-monitoring-complete.md +1578 -0
  347. package/operations/02-playbooks/capacity-planning-playbook.md +620 -0
  348. package/operations/03-checklists/production-launch-checklist.md +365 -0
  349. package/operations/04-antipatterns/operations-antipatterns.md +664 -0
  350. package/operations/05-cases/case-sre-practices.md +581 -0
  351. package/operations/06-glossary/operations-glossary.md +120 -0
  352. package/operations/aiops-anomaly-detection.md +758 -0
  353. package/operations/capacity-planning.md +1061 -0
  354. package/operations/chaos-engineering.md +659 -0
  355. package/operations/incident-command-system.md +38 -0
  356. package/operations/observability-complete.md +442 -0
  357. package/operations/slo-sli-playbook.md +517 -0
  358. package/operations/sre-operations-deep-dive.md +39 -0
  359. package/package.json +8 -0
  360. package/performance/01-standards/performance-and-scalability.md +80 -0
  361. package/performance/01-standards/performance-standards.md +156 -0
  362. package/performance/02-playbooks/query-optimization-playbook.md +103 -0
  363. package/performance/03-checklists/performance-checklist.md +56 -0
  364. package/performance/04-antipatterns/performance-antipatterns.md +146 -0
  365. package/product/01-standards/product-management-complete.md +285 -0
  366. package/product/02-playbooks/feature-launch-playbook.md +207 -0
  367. package/product/02-playbooks/user-research-playbook.md +532 -0
  368. package/product/03-checklists/feature-launch-checklist.md +275 -0
  369. package/product/04-antipatterns/product-antipatterns.md +355 -0
  370. package/product/05-cases/case-mvp-to-scale.md +384 -0
  371. package/product/06-glossary/product-glossary.md +462 -0
  372. package/product/feature-prioritization-framework.md +40 -0
  373. package/product/kpi-and-metric-tree.md +37 -0
  374. package/product/product-discovery-and-prd-deep-dive.md +41 -0
  375. package/quantum/01-standards/quantum-complete.md +1186 -0
  376. package/security/01-standards/api-security-complete.md +511 -0
  377. package/security/01-standards/container-runtime-security.md +574 -0
  378. package/security/01-standards/data-protection-gdpr.md +543 -0
  379. package/security/01-standards/owasp-top10-complete.md +1890 -0
  380. package/security/01-standards/secure-coding-baseline.md +90 -0
  381. package/security/01-standards/supply-chain-security.md +441 -0
  382. package/security/01-standards/web-security-checklist.md +108 -0
  383. package/security/01-standards/zero-trust-architecture.md +521 -0
  384. package/security/02-playbooks/auth-sso-playbook.md +166 -0
  385. package/security/02-playbooks/incident-response-security-playbook.md +588 -0
  386. package/security/02-playbooks/owasp-api-security-playbook.md +129 -0
  387. package/security/02-playbooks/payment-integration-playbook.md +119 -0
  388. package/security/02-playbooks/penetration-testing-playbook.md +517 -0
  389. package/security/03-checklists/security-audit-checklist.md +356 -0
  390. package/security/04-antipatterns/security-coding-antipatterns.md +580 -0
  391. package/security/05-cases/case-log4shell-incident.md +537 -0
  392. package/security/05-cases/case-major-breaches.md +468 -0
  393. package/security/06-glossary/security-glossary.md +212 -0
  394. package/security/compliance-automation.md +993 -0
  395. package/security/container-security.md +680 -0
  396. package/security/devsecops-complete.md +426 -0
  397. package/security/sast-dast-sca.md +775 -0
  398. package/security/secrets-management.md +594 -0
  399. package/security/security-architecture-deep-dive.md +37 -0
  400. package/security/threat-modeling-stride-playbook.md +40 -0
  401. package/seed-templates/auth-system.md +59 -0
  402. package/seed-templates/blog-content.md +94 -0
  403. package/seed-templates/dashboard.md +89 -0
  404. package/seed-templates/docs-site.md +73 -0
  405. package/seed-templates/e-commerce.md +50 -0
  406. package/seed-templates/saas-landing.md +92 -0
  407. package/seed-templates/settings-page.md +51 -0
  408. package/testing/01-standards/test-strategy-and-layering.md +83 -0
  409. package/testing/01-standards/testing-strategy-complete.md +422 -0
  410. package/testing/01-standards/unit-testing-best-practices.md +118 -0
  411. package/testing/02-playbooks/e2e-testing-playbook.md +988 -0
  412. package/testing/02-playbooks/testing-strategy-playbook.md +126 -0
  413. package/testing/03-checklists/test-strategy-checklist.md +208 -0
  414. package/testing/04-antipatterns/testing-antipatterns.md +718 -0
  415. package/testing/05-cases/case-testing-transformation.md +300 -0
  416. package/testing/06-glossary/testing-glossary.md +110 -0
  417. package/testing/risk-based-test-matrix.md +36 -0
  418. package/testing/testing-strategy-deep-dive.md +37 -0
@@ -0,0 +1,1315 @@
1
+ ---
2
+ id: smart-contract-development
3
+ title: 智能合约开发完整指南
4
+ domain: blockchain
5
+ category: 01-standards
6
+ difficulty: intermediate
7
+ tags: [blockchain, contract, development, near, rust, smart, solidity, 优化]
8
+ quality_score: 70
9
+ last_updated: 2026-06-15
10
+ ---
11
+ # 智能合约开发完整指南
12
+
13
+ ## 概述
14
+
15
+ 智能合约是部署在区块链上的自执行程序,一旦部署即不可修改(除非使用代理模式)。本指南覆盖 Solidity 和 Rust 智能合约开发、EVM 原理、Gas 优化、安全审计、测试框架、DeFi/NFT/DAO 开发模式以及 Layer 2 解决方案。
16
+
17
+ ### 智能合约 vs 传统后端
18
+
19
+ | 维度 | 智能合约 | 传统后端 |
20
+ |------|---------|---------|
21
+ | 部署后修改 | 不可变(需代理模式) | 随时可更新 |
22
+ | 执行成本 | 每次调用消耗 Gas | 服务器资源(固定成本) |
23
+ | 状态管理 | 链上存储(极贵) | 数据库(便宜) |
24
+ | 错误处理 | revert 回滚所有状态 | 可部分失败 |
25
+ | 并发 | 串行执行(按区块) | 并行处理 |
26
+ | 审计要求 | 极高(资金安全) | 视业务而定 |
27
+ | 开源透明 | 代码公开可验证 | 可闭源 |
28
+
29
+ ---
30
+
31
+ ## EVM 原理
32
+
33
+ ### 1. 以太坊虚拟机架构
34
+
35
+ ```
36
+ ┌─────────────────────────────────────────┐
37
+ │ Transaction 提交 │
38
+ ├─────────────────────────────────────────┤
39
+ │ EVM 执行环境 │
40
+ │ ┌──────────────────────────────────┐ │
41
+ │ │ Stack (栈) │ │
42
+ │ │ 最大深度 1024, 每个元素 256 bit │ │
43
+ │ ├──────────────────────────────────┤ │
44
+ │ │ Memory (内存) │ │
45
+ │ │ 按字节寻址, 执行后释放 │ │
46
+ │ ├──────────────────────────────────┤ │
47
+ │ │ Storage (存储) │ │
48
+ │ │ 持久化, 按 32 字节 slot 组织 │ │
49
+ │ │ 读: 2100 Gas, 冷写: 20000 Gas │ │
50
+ │ ├──────────────────────────────────┤ │
51
+ │ │ Calldata (调用数据) │ │
52
+ │ │ 只读, 函数参数 │ │
53
+ │ └──────────────────────────────────┘ │
54
+ ├─────────────────────────────────────────┤
55
+ │ World State 更新 │
56
+ └─────────────────────────────────────────┘
57
+ ```
58
+
59
+ ### 2. 存储布局(Storage Layout)
60
+
61
+ ```solidity
62
+ contract StorageLayout {
63
+ // Slot 0: 完整的 32 字节
64
+ uint256 public value1;
65
+
66
+ // Slot 1: 紧凑打包(同一 slot)
67
+ uint128 public value2; // Slot 1 低 16 字节
68
+ uint128 public value3; // Slot 1 高 16 字节
69
+
70
+ // Slot 2: bool 和 address 可打包
71
+ bool public flag; // Slot 2, 1 字节
72
+ address public owner; // Slot 2, 20 字节
73
+
74
+ // Slot 3+: mapping 使用 keccak256(key, slot) 定位
75
+ mapping(address => uint256) public balances;
76
+
77
+ // 动态数组: slot 存长度, 数据在 keccak256(slot) 开始
78
+ uint256[] public dynamicArray;
79
+ }
80
+ ```
81
+
82
+ ### 3. 操作码(Opcodes)与 Gas 成本
83
+
84
+ | 操作码 | Gas 成本 | 说明 |
85
+ |--------|---------|------|
86
+ | ADD/SUB/MUL | 3 | 算术运算 |
87
+ | SLOAD | 2100 (冷) / 100 (热) | 读取存储 |
88
+ | SSTORE | 20000 (新) / 5000 (更新) | 写入存储 |
89
+ | MLOAD/MSTORE | 3 | 内存读写 |
90
+ | CALL | 2600 (冷) / 100 (热) | 外部调用 |
91
+ | CREATE | 32000 | 创建合约 |
92
+ | LOG0-LOG4 | 375-1875 | 事件日志 |
93
+ | SELFDESTRUCT | 5000 | 销毁合约 |
94
+
95
+ ---
96
+
97
+ ## Solidity 开发
98
+
99
+ ### 1. 合约结构最佳实践
100
+
101
+ ```solidity
102
+ // SPDX-License-Identifier: MIT
103
+ pragma solidity ^0.8.20;
104
+
105
+ import "@openzeppelin/contracts/access/Ownable.sol";
106
+ import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
107
+ import "@openzeppelin/contracts/utils/Pausable.sol";
108
+
109
+ /**
110
+ * @title Vault
111
+ * @author Team
112
+ * @notice 安全的资金管理合约
113
+ * @dev 使用 Checks-Effects-Interactions 模式
114
+ */
115
+ contract Vault is Ownable, ReentrancyGuard, Pausable {
116
+ // ============ 常量 ============
117
+ uint256 public constant MAX_DEPOSIT = 100 ether;
118
+ uint256 public constant MIN_DEPOSIT = 0.01 ether;
119
+
120
+ // ============ 状态变量 ============
121
+ mapping(address => uint256) private _balances;
122
+ uint256 private _totalDeposits;
123
+
124
+ // ============ 事件 ============
125
+ event Deposited(address indexed user, uint256 amount);
126
+ event Withdrawn(address indexed user, uint256 amount);
127
+
128
+ // ============ 错误 ============
129
+ error InsufficientBalance(uint256 requested, uint256 available);
130
+ error DepositOutOfRange(uint256 amount);
131
+ error ZeroAddress();
132
+
133
+ // ============ 修饰器 ============
134
+ modifier validAddress(address addr) {
135
+ if (addr == address(0)) revert ZeroAddress();
136
+ _;
137
+ }
138
+
139
+ // ============ 构造函数 ============
140
+ constructor() Ownable(msg.sender) {}
141
+
142
+ // ============ 外部函数 ============
143
+
144
+ /// @notice 存款
145
+ /// @dev 使用 nonReentrant 防重入
146
+ function deposit() external payable nonReentrant whenNotPaused {
147
+ if (msg.value < MIN_DEPOSIT || msg.value > MAX_DEPOSIT) {
148
+ revert DepositOutOfRange(msg.value);
149
+ }
150
+
151
+ // Effects
152
+ _balances[msg.sender] += msg.value;
153
+ _totalDeposits += msg.value;
154
+
155
+ // Events
156
+ emit Deposited(msg.sender, msg.value);
157
+ }
158
+
159
+ /// @notice 取款
160
+ /// @param amount 取款金额
161
+ function withdraw(uint256 amount) external nonReentrant whenNotPaused {
162
+ uint256 balance = _balances[msg.sender];
163
+ if (amount > balance) {
164
+ revert InsufficientBalance(amount, balance);
165
+ }
166
+
167
+ // Effects (先更新状态)
168
+ _balances[msg.sender] = balance - amount;
169
+ _totalDeposits -= amount;
170
+
171
+ // Interactions (最后执行外部调用)
172
+ (bool success, ) = payable(msg.sender).call{value: amount}("");
173
+ require(success, "Transfer failed");
174
+
175
+ emit Withdrawn(msg.sender, amount);
176
+ }
177
+
178
+ // ============ 视图函数 ============
179
+
180
+ function balanceOf(address account) external view returns (uint256) {
181
+ return _balances[account];
182
+ }
183
+
184
+ function totalDeposits() external view returns (uint256) {
185
+ return _totalDeposits;
186
+ }
187
+
188
+ // ============ 管理函数 ============
189
+
190
+ function pause() external onlyOwner {
191
+ _pause();
192
+ }
193
+
194
+ function unpause() external onlyOwner {
195
+ _unpause();
196
+ }
197
+ }
198
+ ```
199
+
200
+ ### 2. 设计模式
201
+
202
+ #### 代理模式(Proxy Pattern - UUPS)
203
+
204
+ ```solidity
205
+ // SPDX-License-Identifier: MIT
206
+ pragma solidity ^0.8.20;
207
+
208
+ import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
209
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
210
+
211
+ contract VaultV1 is UUPSUpgradeable, OwnableUpgradeable {
212
+ uint256 public value;
213
+
214
+ /// @custom:oz-upgrades-unsafe-allow constructor
215
+ constructor() {
216
+ _disableInitializers();
217
+ }
218
+
219
+ function initialize() public initializer {
220
+ __Ownable_init(msg.sender);
221
+ __UUPSUpgradeable_init();
222
+ }
223
+
224
+ function setValue(uint256 _value) external {
225
+ value = _value;
226
+ }
227
+
228
+ function _authorizeUpgrade(address newImplementation)
229
+ internal
230
+ override
231
+ onlyOwner
232
+ {}
233
+ }
234
+
235
+ contract VaultV2 is VaultV1 {
236
+ uint256 public newFeature;
237
+
238
+ function setNewFeature(uint256 _value) external {
239
+ newFeature = _value;
240
+ }
241
+ }
242
+ ```
243
+
244
+ #### 钻石模式(Diamond Pattern - EIP-2535)
245
+
246
+ ```solidity
247
+ // 适用于超大型合约(突破 24KB 限制)
248
+ // Facet A: 存款功能
249
+ contract DepositFacet {
250
+ function deposit() external payable {
251
+ // 存款逻辑
252
+ }
253
+ }
254
+
255
+ // Facet B: 取款功能
256
+ contract WithdrawFacet {
257
+ function withdraw(uint256 amount) external {
258
+ // 取款逻辑
259
+ }
260
+ }
261
+
262
+ // Diamond 合约通过 delegatecall 路由到对应 Facet
263
+ ```
264
+
265
+ ### 3. 常用库和接口
266
+
267
+ ```solidity
268
+ // ERC-20 代币
269
+ import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
270
+ import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
271
+
272
+ contract MyToken is ERC20, ERC20Permit {
273
+ constructor() ERC20("MyToken", "MTK") ERC20Permit("MyToken") {
274
+ _mint(msg.sender, 1_000_000 * 10 ** decimals());
275
+ }
276
+ }
277
+
278
+ // ERC-721 NFT
279
+ import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
280
+ import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
281
+
282
+ contract MyNFT is ERC721, ERC721URIStorage {
283
+ uint256 private _tokenIdCounter;
284
+
285
+ constructor() ERC721("MyNFT", "MNFT") {}
286
+
287
+ function safeMint(address to, string memory uri) public {
288
+ uint256 tokenId = _tokenIdCounter++;
289
+ _safeMint(to, tokenId);
290
+ _setTokenURI(tokenId, uri);
291
+ }
292
+ }
293
+
294
+ // ERC-1155 多代币标准
295
+ import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
296
+
297
+ contract GameItems is ERC1155 {
298
+ uint256 public constant GOLD = 0;
299
+ uint256 public constant SWORD = 1;
300
+ uint256 public constant SHIELD = 2;
301
+
302
+ constructor() ERC1155("https://game.example/api/item/{id}.json") {
303
+ _mint(msg.sender, GOLD, 10**18, "");
304
+ _mint(msg.sender, SWORD, 100, "");
305
+ _mint(msg.sender, SHIELD, 50, "");
306
+ }
307
+ }
308
+ ```
309
+
310
+ ---
311
+
312
+ ## Rust 智能合约(Solana / Near / Ink!)
313
+
314
+ ### 1. Solana (Anchor 框架)
315
+
316
+ ```rust
317
+ use anchor_lang::prelude::*;
318
+
319
+ declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
320
+
321
+ #[program]
322
+ pub mod vault {
323
+ use super::*;
324
+
325
+ pub fn initialize(ctx: Context<Initialize>, bump: u8) -> Result<()> {
326
+ let vault = &mut ctx.accounts.vault;
327
+ vault.authority = ctx.accounts.authority.key();
328
+ vault.total_deposits = 0;
329
+ vault.bump = bump;
330
+ Ok(())
331
+ }
332
+
333
+ pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()> {
334
+ require!(amount > 0, VaultError::ZeroAmount);
335
+
336
+ // 转移 SOL
337
+ let ix = anchor_lang::solana_program::system_instruction::transfer(
338
+ &ctx.accounts.user.key(),
339
+ &ctx.accounts.vault.key(),
340
+ amount,
341
+ );
342
+ anchor_lang::solana_program::program::invoke(
343
+ &ix,
344
+ &[
345
+ ctx.accounts.user.to_account_info(),
346
+ ctx.accounts.vault.to_account_info(),
347
+ ],
348
+ )?;
349
+
350
+ let vault = &mut ctx.accounts.vault;
351
+ vault.total_deposits += amount;
352
+
353
+ emit!(DepositEvent {
354
+ user: ctx.accounts.user.key(),
355
+ amount,
356
+ });
357
+
358
+ Ok(())
359
+ }
360
+ }
361
+
362
+ #[derive(Accounts)]
363
+ pub struct Initialize<'info> {
364
+ #[account(
365
+ init,
366
+ payer = authority,
367
+ space = 8 + Vault::INIT_SPACE,
368
+ seeds = [b"vault"],
369
+ bump,
370
+ )]
371
+ pub vault: Account<'info, Vault>,
372
+ #[account(mut)]
373
+ pub authority: Signer<'info>,
374
+ pub system_program: Program<'info, System>,
375
+ }
376
+
377
+ #[derive(Accounts)]
378
+ pub struct Deposit<'info> {
379
+ #[account(mut, seeds = [b"vault"], bump = vault.bump)]
380
+ pub vault: Account<'info, Vault>,
381
+ #[account(mut)]
382
+ pub user: Signer<'info>,
383
+ pub system_program: Program<'info, System>,
384
+ }
385
+
386
+ #[account]
387
+ #[derive(InitSpace)]
388
+ pub struct Vault {
389
+ pub authority: Pubkey,
390
+ pub total_deposits: u64,
391
+ pub bump: u8,
392
+ }
393
+
394
+ #[event]
395
+ pub struct DepositEvent {
396
+ pub user: Pubkey,
397
+ pub amount: u64,
398
+ }
399
+
400
+ #[error_code]
401
+ pub enum VaultError {
402
+ #[msg("Amount must be greater than zero")]
403
+ ZeroAmount,
404
+ #[msg("Unauthorized access")]
405
+ Unauthorized,
406
+ }
407
+ ```
408
+
409
+ ### 2. Near Protocol
410
+
411
+ ```rust
412
+ use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
413
+ use near_sdk::collections::LookupMap;
414
+ use near_sdk::{env, near_bindgen, AccountId, Balance, Promise};
415
+
416
+ #[near_bindgen]
417
+ #[derive(BorshDeserialize, BorshSerialize)]
418
+ pub struct Vault {
419
+ balances: LookupMap<AccountId, Balance>,
420
+ total_deposits: Balance,
421
+ owner: AccountId,
422
+ }
423
+
424
+ impl Default for Vault {
425
+ fn default() -> Self {
426
+ Self {
427
+ balances: LookupMap::new(b"b"),
428
+ total_deposits: 0,
429
+ owner: env::predecessor_account_id(),
430
+ }
431
+ }
432
+ }
433
+
434
+ #[near_bindgen]
435
+ impl Vault {
436
+ #[payable]
437
+ pub fn deposit(&mut self) {
438
+ let amount = env::attached_deposit();
439
+ assert!(amount > 0, "Deposit must be positive");
440
+
441
+ let account = env::predecessor_account_id();
442
+ let current = self.balances.get(&account).unwrap_or(0);
443
+ self.balances.insert(&account, &(current + amount));
444
+ self.total_deposits += amount;
445
+
446
+ env::log_str(&format!("Deposited {} from {}", amount, account));
447
+ }
448
+
449
+ pub fn withdraw(&mut self, amount: Balance) {
450
+ let account = env::predecessor_account_id();
451
+ let balance = self.balances.get(&account).unwrap_or(0);
452
+ assert!(amount <= balance, "Insufficient balance");
453
+
454
+ self.balances.insert(&account, &(balance - amount));
455
+ self.total_deposits -= amount;
456
+
457
+ Promise::new(account).transfer(amount);
458
+ }
459
+
460
+ pub fn balance_of(&self, account_id: AccountId) -> Balance {
461
+ self.balances.get(&account_id).unwrap_or(0)
462
+ }
463
+ }
464
+ ```
465
+
466
+ ---
467
+
468
+ ## Gas 优化
469
+
470
+ ### 1. 存储优化(最大收益)
471
+
472
+ ```solidity
473
+ // ❌ 每个变量占一个 slot (3 * 32 = 96 bytes)
474
+ contract Unoptimized {
475
+ uint256 public a; // Slot 0
476
+ bool public b; // Slot 1 (浪费 31 bytes)
477
+ uint256 public c; // Slot 2
478
+ }
479
+
480
+ // ✅ 紧凑打包 (64 bytes)
481
+ contract Optimized {
482
+ uint256 public a; // Slot 0
483
+ uint256 public c; // Slot 1
484
+ bool public b; // 与下一个小变量共享 Slot 2
485
+ }
486
+
487
+ // ✅ 结构体打包
488
+ contract StructPacking {
489
+ // ❌ 3 个 slot
490
+ struct BadUser {
491
+ uint256 id;
492
+ bool active;
493
+ uint256 balance;
494
+ }
495
+
496
+ // ✅ 2 个 slot
497
+ struct GoodUser {
498
+ uint256 id; // Slot 0
499
+ uint128 balance; // Slot 1 低 16 字节
500
+ bool active; // Slot 1 (与 balance 共享)
501
+ }
502
+ }
503
+ ```
504
+
505
+ ### 2. 计算优化
506
+
507
+ ```solidity
508
+ contract GasOptimization {
509
+ uint256[] public data;
510
+
511
+ // ❌ 每次循环读取 storage
512
+ function sumBad() external view returns (uint256 total) {
513
+ for (uint256 i = 0; i < data.length; i++) {
514
+ total += data[i];
515
+ }
516
+ }
517
+
518
+ // ✅ 缓存到 memory
519
+ function sumGood() external view returns (uint256 total) {
520
+ uint256[] memory _data = data;
521
+ uint256 len = _data.length;
522
+ for (uint256 i = 0; i < len; i++) {
523
+ total += _data[i];
524
+ }
525
+ }
526
+
527
+ // ✅ 使用 unchecked 跳过溢出检查(已知安全时)
528
+ function sumBest() external view returns (uint256 total) {
529
+ uint256[] memory _data = data;
530
+ uint256 len = _data.length;
531
+ for (uint256 i = 0; i < len; ) {
532
+ total += _data[i];
533
+ unchecked { ++i; }
534
+ }
535
+ }
536
+
537
+ // ✅ 使用 calldata 替代 memory(只读参数)
538
+ function processCalldata(uint256[] calldata items)
539
+ external
540
+ pure
541
+ returns (uint256 total)
542
+ {
543
+ for (uint256 i = 0; i < items.length; ) {
544
+ total += items[i];
545
+ unchecked { ++i; }
546
+ }
547
+ }
548
+
549
+ // ✅ 使用 custom error 替代 require string
550
+ error Unauthorized();
551
+ error InvalidAmount(uint256 amount);
552
+
553
+ function optimizedRequire(uint256 amount) external view {
554
+ if (msg.sender == address(0)) revert Unauthorized();
555
+ if (amount == 0) revert InvalidAmount(amount);
556
+ }
557
+ }
558
+ ```
559
+
560
+ ### 3. 事件优化
561
+
562
+ ```solidity
563
+ contract EventOptimization {
564
+ // ✅ 使用 indexed 参数(便于过滤,但增加少量 Gas)
565
+ event Transfer(
566
+ address indexed from,
567
+ address indexed to,
568
+ uint256 amount // 非 indexed,存储在 data 中
569
+ );
570
+
571
+ // ✅ 大量数据用事件而非 storage(便宜 5-10 倍)
572
+ // 事件数据无法在合约中读取,但前端可以
573
+ event DataStored(bytes32 indexed key, bytes data);
574
+ }
575
+ ```
576
+
577
+ ### Gas 优化速查表
578
+
579
+ | 技巧 | 节省 Gas | 风险等级 |
580
+ |------|---------|---------|
581
+ | 变量打包(slot packing) | 15000-20000 | 低 |
582
+ | 用 calldata 替代 memory | 500-5000 | 低 |
583
+ | 缓存 storage 到 memory | 2000+ per read | 低 |
584
+ | unchecked 算术 | 100-300 per op | 中(需确保安全) |
585
+ | Custom error 替代 string | 200-1000 | 低 |
586
+ | 短路求值优化 | 100-500 | 低 |
587
+ | 使用 immutable/constant | 2000+ | 低 |
588
+ | 批量操作替代多次调用 | 21000 per tx saved | 低 |
589
+
590
+ ---
591
+
592
+ ## 安全审计
593
+
594
+ ### 1. 重入攻击(Reentrancy)
595
+
596
+ **攻击原理**:
597
+ ```solidity
598
+ // 漏洞合约
599
+ contract VulnerableVault {
600
+ mapping(address => uint256) public balances;
601
+
602
+ function withdraw() external {
603
+ uint256 amount = balances[msg.sender];
604
+ // ❌ 先发送 ETH,再更新状态
605
+ (bool success, ) = msg.sender.call{value: amount}("");
606
+ require(success);
607
+ balances[msg.sender] = 0; // 攻击者在此之前重新进入
608
+ }
609
+ }
610
+
611
+ // 攻击合约
612
+ contract Attacker {
613
+ VulnerableVault public vault;
614
+
615
+ function attack() external payable {
616
+ vault.deposit{value: 1 ether}();
617
+ vault.withdraw();
618
+ }
619
+
620
+ receive() external payable {
621
+ if (address(vault).balance >= 1 ether) {
622
+ vault.withdraw(); // 重入!状态尚未更新
623
+ }
624
+ }
625
+ }
626
+ ```
627
+
628
+ **防御方案**:
629
+ ```solidity
630
+ contract SafeVault {
631
+ mapping(address => uint256) public balances;
632
+ bool private _locked;
633
+
634
+ // 方案 1: Checks-Effects-Interactions 模式
635
+ function withdraw() external {
636
+ uint256 amount = balances[msg.sender];
637
+ require(amount > 0, "No balance");
638
+
639
+ // Effects(先更新状态)
640
+ balances[msg.sender] = 0;
641
+
642
+ // Interactions(后执行外部调用)
643
+ (bool success, ) = msg.sender.call{value: amount}("");
644
+ require(success);
645
+ }
646
+
647
+ // 方案 2: ReentrancyGuard
648
+ modifier nonReentrant() {
649
+ require(!_locked, "Reentrant call");
650
+ _locked = true;
651
+ _;
652
+ _locked = false;
653
+ }
654
+
655
+ function withdrawSafe() external nonReentrant {
656
+ uint256 amount = balances[msg.sender];
657
+ balances[msg.sender] = 0;
658
+ (bool success, ) = msg.sender.call{value: amount}("");
659
+ require(success);
660
+ }
661
+ }
662
+ ```
663
+
664
+ ### 2. 整数溢出(Integer Overflow/Underflow)
665
+
666
+ ```solidity
667
+ // Solidity 0.8+ 默认有溢出检查,但 unchecked 块中仍需注意
668
+
669
+ contract IntegerSafety {
670
+ // ✅ 0.8+ 默认安全
671
+ function safeAdd(uint256 a, uint256 b) external pure returns (uint256) {
672
+ return a + b; // 溢出会自动 revert
673
+ }
674
+
675
+ // ❌ unchecked 中不安全
676
+ function unsafeAdd(uint256 a, uint256 b) external pure returns (uint256) {
677
+ unchecked {
678
+ return a + b; // 可能溢出!
679
+ }
680
+ }
681
+
682
+ // ✅ 安全的类型转换
683
+ function safeCast(uint256 value) external pure returns (uint128) {
684
+ require(value <= type(uint128).max, "Overflow");
685
+ return uint128(value);
686
+ }
687
+ }
688
+ ```
689
+
690
+ ### 3. 授权漏洞(Access Control)
691
+
692
+ ```solidity
693
+ contract AccessControlExample {
694
+ // ❌ 缺少权限检查
695
+ function dangerousFunction() external {
696
+ // 任何人都可以调用!
697
+ }
698
+
699
+ // ❌ 使用 tx.origin(可被钓鱼攻击)
700
+ function badAuth() external {
701
+ require(tx.origin == owner); // 不安全!
702
+ }
703
+
704
+ // ✅ 使用 OpenZeppelin AccessControl
705
+ // 多角色权限管理
706
+ bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
707
+ bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
708
+
709
+ function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
710
+ _mint(to, amount);
711
+ }
712
+
713
+ // ✅ 时间锁(Timelock)
714
+ uint256 public constant TIMELOCK_DELAY = 2 days;
715
+ mapping(bytes32 => uint256) public pendingActions;
716
+
717
+ function scheduleAction(bytes32 actionId) external onlyOwner {
718
+ pendingActions[actionId] = block.timestamp + TIMELOCK_DELAY;
719
+ }
720
+
721
+ function executeAction(bytes32 actionId) external onlyOwner {
722
+ require(pendingActions[actionId] != 0, "Not scheduled");
723
+ require(block.timestamp >= pendingActions[actionId], "Too early");
724
+ delete pendingActions[actionId];
725
+ // 执行操作
726
+ }
727
+ }
728
+ ```
729
+
730
+ ### 4. 其他常见漏洞
731
+
732
+ ```solidity
733
+ // ❌ 前置交易攻击(Front-running)
734
+ contract VulnerableAuction {
735
+ function bid() external payable {
736
+ // 攻击者可以看到 mempool 中的交易并抢先出价
737
+ }
738
+ }
739
+
740
+ // ✅ 使用 commit-reveal 方案
741
+ contract SafeAuction {
742
+ mapping(address => bytes32) public commits;
743
+
744
+ function commit(bytes32 hash) external {
745
+ commits[msg.sender] = hash;
746
+ }
747
+
748
+ function reveal(uint256 amount, bytes32 salt) external payable {
749
+ require(
750
+ keccak256(abi.encodePacked(amount, salt)) == commits[msg.sender],
751
+ "Invalid reveal"
752
+ );
753
+ // 处理出价
754
+ }
755
+ }
756
+
757
+ // ❌ 闪电贷攻击防御
758
+ // 关键: 不要在单笔交易中依赖价格预言机的即时值
759
+ contract SafePricing {
760
+ // ✅ 使用 TWAP(时间加权平均价格)
761
+ function getPrice() external view returns (uint256) {
762
+ // 使用 Uniswap V3 TWAP Oracle
763
+ // 而不是即时 spot price
764
+ }
765
+ }
766
+ ```
767
+
768
+ ### 安全审计清单
769
+
770
+ | 检查项 | 严重性 | 工具 |
771
+ |--------|--------|------|
772
+ | 重入攻击 | Critical | Slither, Mythril |
773
+ | 整数溢出 | High | Solidity 0.8+ 内建 |
774
+ | 权限控制 | Critical | 手动审查 |
775
+ | 前置交易 | Medium | 架构设计 |
776
+ | 闪电贷攻击 | High | 手动审查 |
777
+ | 未检查返回值 | High | Slither |
778
+ | Gas 限制 DoS | Medium | 手动审查 |
779
+ | 时间戳依赖 | Low | Slither |
780
+ | 随机数不安全 | High | 手动审查 |
781
+ | 自毁漏洞 | Medium | Mythril |
782
+
783
+ ---
784
+
785
+ ## 测试框架
786
+
787
+ ### 1. Foundry(推荐)
788
+
789
+ ```solidity
790
+ // test/Vault.t.sol
791
+ // SPDX-License-Identifier: MIT
792
+ pragma solidity ^0.8.20;
793
+
794
+ import "forge-std/Test.sol";
795
+ import "../src/Vault.sol";
796
+
797
+ contract VaultTest is Test {
798
+ Vault public vault;
799
+ address public alice = makeAddr("alice");
800
+ address public bob = makeAddr("bob");
801
+
802
+ function setUp() public {
803
+ vault = new Vault();
804
+ vm.deal(alice, 100 ether);
805
+ vm.deal(bob, 100 ether);
806
+ }
807
+
808
+ function test_Deposit() public {
809
+ vm.prank(alice);
810
+ vault.deposit{value: 1 ether}();
811
+
812
+ assertEq(vault.balanceOf(alice), 1 ether);
813
+ assertEq(vault.totalDeposits(), 1 ether);
814
+ }
815
+
816
+ function test_Withdraw() public {
817
+ vm.startPrank(alice);
818
+ vault.deposit{value: 5 ether}();
819
+ vault.withdraw(2 ether);
820
+ vm.stopPrank();
821
+
822
+ assertEq(vault.balanceOf(alice), 3 ether);
823
+ }
824
+
825
+ function test_RevertWhen_InsufficientBalance() public {
826
+ vm.prank(alice);
827
+ vm.expectRevert(
828
+ abi.encodeWithSelector(
829
+ Vault.InsufficientBalance.selector,
830
+ 1 ether,
831
+ 0
832
+ )
833
+ );
834
+ vault.withdraw(1 ether);
835
+ }
836
+
837
+ // Fuzz 测试
838
+ function testFuzz_Deposit(uint256 amount) public {
839
+ amount = bound(amount, 0.01 ether, 100 ether);
840
+
841
+ vm.prank(alice);
842
+ vault.deposit{value: amount}();
843
+
844
+ assertEq(vault.balanceOf(alice), amount);
845
+ }
846
+
847
+ // 不变量测试
848
+ function invariant_TotalDepositsMatchBalance() public view {
849
+ assertEq(
850
+ vault.totalDeposits(),
851
+ address(vault).balance
852
+ );
853
+ }
854
+ }
855
+ ```
856
+
857
+ **Foundry 命令**:
858
+ ```bash
859
+ # 运行所有测试
860
+ forge test
861
+
862
+ # 详细输出
863
+ forge test -vvvv
864
+
865
+ # 运行单个测试
866
+ forge test --match-test test_Deposit
867
+
868
+ # Gas 报告
869
+ forge test --gas-report
870
+
871
+ # 覆盖率
872
+ forge coverage
873
+
874
+ # 部署
875
+ forge script script/Deploy.s.sol --rpc-url $RPC_URL --broadcast
876
+
877
+ # 验证合约
878
+ forge verify-contract $ADDRESS src/Vault.sol:Vault --etherscan-api-key $KEY
879
+ ```
880
+
881
+ ### 2. Hardhat
882
+
883
+ ```javascript
884
+ // test/Vault.test.js
885
+ const { expect } = require("chai");
886
+ const { ethers } = require("hardhat");
887
+ const { loadFixture } = require("@nomicfoundation/hardhat-network-helpers");
888
+
889
+ describe("Vault", function () {
890
+ async function deployFixture() {
891
+ const [owner, alice, bob] = await ethers.getSigners();
892
+ const Vault = await ethers.getContractFactory("Vault");
893
+ const vault = await Vault.deploy();
894
+ return { vault, owner, alice, bob };
895
+ }
896
+
897
+ describe("Deposit", function () {
898
+ it("should accept deposits", async function () {
899
+ const { vault, alice } = await loadFixture(deployFixture);
900
+
901
+ await vault.connect(alice).deposit({
902
+ value: ethers.parseEther("1.0")
903
+ });
904
+
905
+ expect(await vault.balanceOf(alice.address))
906
+ .to.equal(ethers.parseEther("1.0"));
907
+ });
908
+
909
+ it("should emit Deposited event", async function () {
910
+ const { vault, alice } = await loadFixture(deployFixture);
911
+
912
+ await expect(
913
+ vault.connect(alice).deposit({ value: ethers.parseEther("1.0") })
914
+ ).to.emit(vault, "Deposited")
915
+ .withArgs(alice.address, ethers.parseEther("1.0"));
916
+ });
917
+
918
+ it("should revert on zero deposit", async function () {
919
+ const { vault, alice } = await loadFixture(deployFixture);
920
+
921
+ await expect(
922
+ vault.connect(alice).deposit({ value: 0 })
923
+ ).to.be.revertedWithCustomError(vault, "DepositOutOfRange");
924
+ });
925
+ });
926
+
927
+ describe("Withdraw", function () {
928
+ it("should allow withdrawal", async function () {
929
+ const { vault, alice } = await loadFixture(deployFixture);
930
+
931
+ await vault.connect(alice).deposit({
932
+ value: ethers.parseEther("5.0")
933
+ });
934
+
935
+ const balanceBefore = await ethers.provider.getBalance(alice.address);
936
+ const tx = await vault.connect(alice).withdraw(ethers.parseEther("2.0"));
937
+ const receipt = await tx.wait();
938
+ const gasUsed = receipt.gasUsed * receipt.gasPrice;
939
+ const balanceAfter = await ethers.provider.getBalance(alice.address);
940
+
941
+ expect(balanceAfter - balanceBefore + gasUsed)
942
+ .to.equal(ethers.parseEther("2.0"));
943
+ });
944
+ });
945
+ });
946
+ ```
947
+
948
+ ---
949
+
950
+ ## DeFi 开发模式
951
+
952
+ ### 1. AMM(自动做市商)
953
+
954
+ ```solidity
955
+ // 简化的 Constant Product AMM (x * y = k)
956
+ contract SimpleAMM {
957
+ IERC20 public tokenA;
958
+ IERC20 public tokenB;
959
+ uint256 public reserveA;
960
+ uint256 public reserveB;
961
+
962
+ uint256 public constant FEE_NUMERATOR = 3;
963
+ uint256 public constant FEE_DENOMINATOR = 1000; // 0.3% fee
964
+
965
+ function swap(address tokenIn, uint256 amountIn) external returns (uint256 amountOut) {
966
+ require(amountIn > 0, "Zero amount");
967
+
968
+ bool isTokenA = tokenIn == address(tokenA);
969
+ (uint256 reserveIn, uint256 reserveOut) = isTokenA
970
+ ? (reserveA, reserveB)
971
+ : (reserveB, reserveA);
972
+
973
+ // 扣除手续费
974
+ uint256 amountInWithFee = amountIn * (FEE_DENOMINATOR - FEE_NUMERATOR);
975
+
976
+ // x * y = k => amountOut = reserveOut * amountInWithFee / (reserveIn * 1000 + amountInWithFee)
977
+ amountOut = (reserveOut * amountInWithFee) /
978
+ (reserveIn * FEE_DENOMINATOR + amountInWithFee);
979
+
980
+ // 更新储备
981
+ if (isTokenA) {
982
+ reserveA += amountIn;
983
+ reserveB -= amountOut;
984
+ tokenA.transferFrom(msg.sender, address(this), amountIn);
985
+ tokenB.transfer(msg.sender, amountOut);
986
+ } else {
987
+ reserveB += amountIn;
988
+ reserveA -= amountOut;
989
+ tokenB.transferFrom(msg.sender, address(this), amountIn);
990
+ tokenA.transfer(msg.sender, amountOut);
991
+ }
992
+ }
993
+ }
994
+ ```
995
+
996
+ ### 2. 借贷协议核心逻辑
997
+
998
+ ```solidity
999
+ contract SimpleLending {
1000
+ struct Market {
1001
+ uint256 totalDeposits;
1002
+ uint256 totalBorrows;
1003
+ uint256 interestRate; // 年化利率 (basis points)
1004
+ uint256 collateralFactor; // 抵押率 (basis points, e.g., 7500 = 75%)
1005
+ }
1006
+
1007
+ mapping(address => Market) public markets;
1008
+ mapping(address => mapping(address => uint256)) public deposits;
1009
+ mapping(address => mapping(address => uint256)) public borrows;
1010
+
1011
+ function supply(address token, uint256 amount) external {
1012
+ IERC20(token).transferFrom(msg.sender, address(this), amount);
1013
+ deposits[msg.sender][token] += amount;
1014
+ markets[token].totalDeposits += amount;
1015
+ }
1016
+
1017
+ function borrow(address token, uint256 amount) external {
1018
+ // 检查抵押率
1019
+ uint256 collateralValue = getCollateralValue(msg.sender);
1020
+ uint256 borrowValue = getBorrowValue(msg.sender) + getTokenValue(token, amount);
1021
+ require(
1022
+ borrowValue * 10000 <= collateralValue * markets[token].collateralFactor,
1023
+ "Insufficient collateral"
1024
+ );
1025
+
1026
+ borrows[msg.sender][token] += amount;
1027
+ markets[token].totalBorrows += amount;
1028
+ IERC20(token).transfer(msg.sender, amount);
1029
+ }
1030
+ }
1031
+ ```
1032
+
1033
+ ### 3. NFT 开发模式
1034
+
1035
+ ```solidity
1036
+ // ERC-721A 批量铸造(Gas 优化)
1037
+ import "erc721a/contracts/ERC721A.sol";
1038
+
1039
+ contract OptimizedNFT is ERC721A {
1040
+ uint256 public constant MAX_SUPPLY = 10000;
1041
+ uint256 public constant MINT_PRICE = 0.08 ether;
1042
+ uint256 public constant MAX_PER_TX = 10;
1043
+
1044
+ string private _baseTokenURI;
1045
+ bool public mintActive;
1046
+
1047
+ constructor() ERC721A("OptimizedNFT", "ONFT") {}
1048
+
1049
+ function mint(uint256 quantity) external payable {
1050
+ require(mintActive, "Mint not active");
1051
+ require(quantity <= MAX_PER_TX, "Exceeds max per tx");
1052
+ require(totalSupply() + quantity <= MAX_SUPPLY, "Exceeds supply");
1053
+ require(msg.value >= MINT_PRICE * quantity, "Insufficient payment");
1054
+
1055
+ _mint(msg.sender, quantity);
1056
+ }
1057
+
1058
+ // Merkle Tree 白名单
1059
+ bytes32 public merkleRoot;
1060
+
1061
+ function whitelistMint(uint256 quantity, bytes32[] calldata proof)
1062
+ external
1063
+ payable
1064
+ {
1065
+ bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
1066
+ require(
1067
+ MerkleProof.verify(proof, merkleRoot, leaf),
1068
+ "Not whitelisted"
1069
+ );
1070
+ _mint(msg.sender, quantity);
1071
+ }
1072
+ }
1073
+ ```
1074
+
1075
+ ### 4. DAO 治理模式
1076
+
1077
+ ```solidity
1078
+ import "@openzeppelin/contracts/governance/Governor.sol";
1079
+ import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";
1080
+ import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";
1081
+ import "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol";
1082
+
1083
+ contract MyDAO is
1084
+ Governor,
1085
+ GovernorCountingSimple,
1086
+ GovernorVotes,
1087
+ GovernorTimelockControl
1088
+ {
1089
+ constructor(
1090
+ IVotes _token,
1091
+ TimelockController _timelock
1092
+ )
1093
+ Governor("MyDAO")
1094
+ GovernorVotes(_token)
1095
+ GovernorTimelockControl(_timelock)
1096
+ {}
1097
+
1098
+ function votingDelay() public pure override returns (uint256) {
1099
+ return 1 days; // 投票延迟
1100
+ }
1101
+
1102
+ function votingPeriod() public pure override returns (uint256) {
1103
+ return 1 weeks; // 投票持续时间
1104
+ }
1105
+
1106
+ function quorum(uint256) public pure override returns (uint256) {
1107
+ return 100_000e18; // 法定人数(代币数量)
1108
+ }
1109
+
1110
+ function proposalThreshold() public pure override returns (uint256) {
1111
+ return 1000e18; // 提案门槛
1112
+ }
1113
+ }
1114
+ ```
1115
+
1116
+ ---
1117
+
1118
+ ## Layer 2 解决方案
1119
+
1120
+ ### 1. Rollup 概览
1121
+
1122
+ ```
1123
+ ┌──────────────────────────────────────────────┐
1124
+ │ Layer 1 (以太坊) │
1125
+ │ ┌──────────────┐ ┌──────────────────────┐ │
1126
+ │ │ Rollup 合约 │ │ 数据可用性层 │ │
1127
+ │ │ (验证证明) │ │ (存储交易数据) │ │
1128
+ │ └──────────────┘ └──────────────────────┘ │
1129
+ ├──────────────────────────────────────────────┤
1130
+ │ Layer 2 (Rollup) │
1131
+ │ ┌──────────────┐ ┌──────────────────────┐ │
1132
+ │ │ 排序器 │ │ 执行环境 │ │
1133
+ │ │ (Sequencer) │ │ (交易处理) │ │
1134
+ │ └──────────────┘ └──────────────────────┘ │
1135
+ └──────────────────────────────────────────────┘
1136
+ ```
1137
+
1138
+ ### 2. Optimistic Rollup vs ZK Rollup
1139
+
1140
+ | 维度 | Optimistic Rollup | ZK Rollup |
1141
+ |------|-------------------|-----------|
1142
+ | 代表项目 | Optimism, Arbitrum, Base | zkSync, StarkNet, Scroll |
1143
+ | 验证机制 | 欺诈证明(挑战期 7 天) | 零知识证明(即时验证) |
1144
+ | 提款时间 | 7 天(原生桥) | 分钟级 |
1145
+ | Gas 成本 | 较低 | 中等(证明生成成本) |
1146
+ | EVM 兼容性 | 高(几乎完全兼容) | 中-高(不断改善) |
1147
+ | 适合场景 | 通用 DApp | 高频交易、支付 |
1148
+ | 开发难度 | 低(与 L1 几乎相同) | 中(需了解 ZK 限制) |
1149
+
1150
+ ### 3. Optimistic Rollup 开发(Optimism/Base)
1151
+
1152
+ ```javascript
1153
+ // 在 Optimism/Base 上部署与 L1 几乎相同
1154
+ // hardhat.config.js
1155
+ module.exports = {
1156
+ networks: {
1157
+ optimism: {
1158
+ url: "https://mainnet.optimism.io",
1159
+ chainId: 10,
1160
+ accounts: [process.env.PRIVATE_KEY]
1161
+ },
1162
+ base: {
1163
+ url: "https://mainnet.base.org",
1164
+ chainId: 8453,
1165
+ accounts: [process.env.PRIVATE_KEY]
1166
+ },
1167
+ arbitrum: {
1168
+ url: "https://arb1.arbitrum.io/rpc",
1169
+ chainId: 42161,
1170
+ accounts: [process.env.PRIVATE_KEY]
1171
+ }
1172
+ }
1173
+ };
1174
+
1175
+ // L1 <-> L2 消息传递 (Optimism)
1176
+ const { CrossChainMessenger } = require("@eth-optimism/sdk");
1177
+
1178
+ const messenger = new CrossChainMessenger({
1179
+ l1ChainId: 1,
1180
+ l2ChainId: 10,
1181
+ l1SignerOrProvider: l1Signer,
1182
+ l2SignerOrProvider: l2Signer,
1183
+ });
1184
+
1185
+ // L1 -> L2 存款
1186
+ await messenger.depositETH(ethers.parseEther("1.0"));
1187
+
1188
+ // L2 -> L1 提款(需等待挑战期)
1189
+ await messenger.withdrawETH(ethers.parseEther("0.5"));
1190
+ ```
1191
+
1192
+ ### 4. ZK Rollup 基础概念
1193
+
1194
+ ```
1195
+ 零知识证明核心思想:
1196
+ 证明者可以向验证者证明自己知道某个信息,
1197
+ 而无需透露该信息本身。
1198
+
1199
+ ZK-SNARK: 简洁非交互式知识论证
1200
+ - 证明大小: 恒定(~200 bytes)
1201
+ - 验证时间: 恒定(~几毫秒)
1202
+ - 需要可信设置(Trusted Setup)
1203
+
1204
+ ZK-STARK: 可扩展透明知识论证
1205
+ - 证明大小: 更大(~KB 级)
1206
+ - 验证时间: 对数级
1207
+ - 无需可信设置
1208
+ - 抗量子计算
1209
+ ```
1210
+
1211
+ **zkSync 开发示例**:
1212
+ ```bash
1213
+ # 使用 zkSync CLI
1214
+ npx zksync-cli create my-project --template hardhat_solidity
1215
+
1216
+ # 部署到 zkSync
1217
+ npx hardhat deploy-zksync --script deploy.ts --network zkSyncTestnet
1218
+ ```
1219
+
1220
+ ---
1221
+
1222
+ ## 开发工具链
1223
+
1224
+ ### 常用工具对比
1225
+
1226
+ | 工具 | 类型 | 语言 | 特点 |
1227
+ |------|------|------|------|
1228
+ | Foundry | 开发框架 | Solidity | 速度快、Solidity 原生测试 |
1229
+ | Hardhat | 开发框架 | JavaScript | 生态丰富、插件多 |
1230
+ | Remix | 在线 IDE | Solidity | 零配置、适合学习 |
1231
+ | Slither | 静态分析 | Python | 漏洞检测、代码质量 |
1232
+ | Mythril | 符号执行 | Python | 深度安全分析 |
1233
+ | Tenderly | 调试/监控 | SaaS | 交易模拟、监控告警 |
1234
+ | Etherscan | 区块浏览器 | SaaS | 合约验证、交易查看 |
1235
+
1236
+ ### 安全分析命令
1237
+
1238
+ ```bash
1239
+ # Slither 静态分析
1240
+ slither src/Vault.sol --solc-remaps "@openzeppelin=node_modules/@openzeppelin"
1241
+
1242
+ # Mythril 符号执行
1243
+ myth analyze src/Vault.sol --solc-json mythril.config.json
1244
+
1245
+ # Foundry 模糊测试
1246
+ forge test --fuzz-runs 10000
1247
+
1248
+ # 合约大小检查(24KB 限制)
1249
+ forge build --sizes
1250
+ ```
1251
+
1252
+ ---
1253
+
1254
+ ## Agent Checklist
1255
+
1256
+ ### 合约设计阶段
1257
+ - [ ] 确认目标链和 EVM 兼容性
1258
+ - [ ] 设计存储布局(变量打包优化)
1259
+ - [ ] 确定升级策略(不可变 / UUPS / Transparent / Diamond)
1260
+ - [ ] 权限模型设计(Ownable / AccessControl / 多签)
1261
+ - [ ] 确认代币标准(ERC-20 / ERC-721 / ERC-1155)
1262
+ - [ ] 设计紧急机制(Pausable / 时间锁)
1263
+
1264
+ ### 开发阶段
1265
+ - [ ] 使用 Solidity 0.8.20+(内建溢出检查)
1266
+ - [ ] 遵循 Checks-Effects-Interactions 模式
1267
+ - [ ] 使用 OpenZeppelin 标准库
1268
+ - [ ] 所有外部调用使用 ReentrancyGuard
1269
+ - [ ] Custom error 替代 require string
1270
+ - [ ] 事件覆盖所有状态变更
1271
+ - [ ] NatSpec 注释完整
1272
+
1273
+ ### Gas 优化阶段
1274
+ - [ ] 变量 slot 打包
1275
+ - [ ] 使用 calldata 替代 memory(只读参数)
1276
+ - [ ] 循环中缓存 storage 变量
1277
+ - [ ] 使用 immutable/constant
1278
+ - [ ] unchecked 用于已知安全的算术
1279
+ - [ ] 批量操作减少交易数
1280
+
1281
+ ### 安全审计阶段
1282
+ - [ ] Slither 静态分析无高危告警
1283
+ - [ ] Mythril 符号执行通过
1284
+ - [ ] Foundry fuzz testing 覆盖边界条件
1285
+ - [ ] 重入攻击测试
1286
+ - [ ] 权限边界测试
1287
+ - [ ] 整数边界测试
1288
+ - [ ] 闪电贷攻击场景评估
1289
+ - [ ] 前置交易风险评估
1290
+
1291
+ ### 测试阶段
1292
+ - [ ] 单元测试覆盖率 > 95%
1293
+ - [ ] Fuzz 测试覆盖关键函数
1294
+ - [ ] 不变量测试定义
1295
+ - [ ] Fork 测试(使用主网状态)
1296
+ - [ ] Gas 报告生成并优化
1297
+ - [ ] 边界条件测试(0值、最大值、空地址)
1298
+
1299
+ ### 部署阶段
1300
+ - [ ] 测试网部署并验证
1301
+ - [ ] 合约代码在 Etherscan 验证
1302
+ - [ ] 多签或时间锁保护管理功能
1303
+ - [ ] 前端集成测试通过
1304
+ - [ ] 监控和告警配置(Tenderly / OpenZeppelin Defender)
1305
+ - [ ] 应急响应计划准备
1306
+
1307
+ ---
1308
+
1309
+ **知识ID**: `smart-contract-development`
1310
+ **领域**: blockchain
1311
+ **类型**: standards
1312
+ **难度**: advanced
1313
+ **质量分**: 93
1314
+ **维护者**: blockchain-team@umadev.com
1315
+ **最后更新**: 2026-03-28