AlgorandTypeScript智能合约开发指南 algorand-typescript

Algorand TypeScript (PuyaTs) 智能合约开发技能,提供语法规则、类型系统、存储模式、交易处理等核心知识。关键词:Algorand, TypeScript, 智能合约, Puya编译器, AVM类型, BoxMap, GlobalState, clone(), 区块链开发, Web3, DApp

智能合约 0 次安装 0 次浏览 更新于 3/4/2026

名称: algorand-typescript 描述: Algorand TypeScript (PuyaTs) 智能合约的语法规则和模式。适用于编写TypeScript合约代码、遇到Puya编译器错误、询问AVM类型或值语义、需要存储模式(GlobalState、BoxMap)指导,或询问clone()、数组或内部事务时。强触发词包括“Puya编译器错误”、“如何使用uint64?”、“clone()有什么用?”、“BoxMap不工作”、“AVM类型错误”、“GlobalState未更新”。

Algorand TypeScript 规则

防止编译器错误和运行时故障的Algorand TypeScript (PuyaTs) 关键语法规则。

文件扩展名:合约文件必须使用 .algo.ts 扩展名(例如 Counter.algo.ts)。

概述 / 核心工作流程

  1. 识别语法问题或所需模式
  2. 应用正确的AVM兼容模式
  3. 对复杂类型使用 clone()
  4. 验证没有联合类型或JavaScript number

如何操作

  1. 检查以下最关键规则
  2. 查阅详细参考文件以了解特定主题
  3. 应用正确模式并配合适当的AVM类型
  4. 构建验证algokit project run build

重要规则 / 指南

数字:禁用JavaScript number

// 正确
const amount: uint64 = Uint64(20)
const total: uint64 = amount + Uint64(100)

// 错误 - 编译器错误
const amount = 20

数值限制:Algorand TypeScript 支持最大2^512的整数。对于超过uint64(2^64 - 1)的值,请使用 biguint

值语义:始终使用 clone()

import { clone } from '@algorandfoundation/algorand-typescript'

const state = clone(this.appState.value)     // 读取:clone
const updated = clone(state)                  // 修改:clone
this.appState.value = clone(updated)          // 写入:clone

禁用联合类型

// 正确 - 使用布尔标志
let found = false
let foundItem: Item = { /* 默认值 */ }

// 错误 - 编译器错误
let foundItem: Item | null = null

数组:迭代前克隆

// 正确
for (const item of clone(array)) { }

常见变体 / 边缘情况

主题 规则
数字 使用 uint64 + Uint64(),绝不使用 number
字符串 不使用 .length;用 text !== '' 检查是否为空
存储 对复杂类型,读取和写入时都需克隆
数组 迭代前克隆;索引必须是 uint64
无类属性;使用模块级常量
方法 公共 = ABI方法;私有 = 子程序

参考 / 延伸阅读

按主题分类的详细规则: