You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Truffle migrate部署合约报ReferenceError: transfer未定义错误

Truffle 部署报错ReferenceError: transfer is not defined修复

问题复现

执行truffle migrate命令部署智能合约时终端持续抛出引用错误,原始部署脚本代码如下:

const Tether = artifacts.require('Tether')
const Reward = artifacts.require('Reward')
const DBank = artifacts.require('DBank')

module.exports = async function (deployer, network, accounts) {
  await deployer.deploy(Tether)
  const tether = await Tether.deployed()

  await deployer.deploy(Reward) 
  const reward = await Reward.deployed()

  await  await deployer.deploy(DBank, reward.address, tether.address)
  const dbank = await DBank.deployed()

  //Transfer all reward tokens to the bank
  await transfer(dbank.address, '1000000000000000000000000')

  //Distribute 100 tokens to the Investor automatically
  await tether.transfer(accounts[1], '100000000000000000') 
};

报错触发原因

该错误属于JavaScript作用域下的未定义函数引用问题:

  • 脚本中await transfer(dbank.address, '1000000000000000000000000')直接调用了名为transfer的函数,但当前函数作用域、Node全局作用域均未定义该独立函数,因此直接抛出引用错误。
  • 结合代码上下文,该行逻辑是将部署完成的Reward奖励代币全部转入DBank合约地址,transfer是ERC20标准代币合约的实例方法,必须绑定对应的已部署合约实例才能调用。对比后续Tether代币转账的写法tether.transfer(accounts[1], ...),可明显看出该行漏写了调用主体reward。

修复方案

将裸调用的transfer改为通过已部署的reward合约实例调用,修复后对应代码段为:

//Transfer all reward tokens to the bank
await reward.transfer(dbank.address, '1000000000000000000000000')

修复后完整可运行部署脚本:

const Tether = artifacts.require('Tether')
const Reward = artifacts.require('Reward')
const DBank = artifacts.require('DBank')

module.exports = async function (deployer, network, accounts) {
  await deployer.deploy(Tether)
  const tether = await Tether.deployed()

  await deployer.deploy(Reward) 
  const reward = await Reward.deployed()

  await deployer.deploy(DBank, reward.address, tether.address)
  const dbank = await DBank.deployed()

  //Transfer all reward tokens to the bank
  await reward.transfer(dbank.address, '1000000000000000000000000')

  //Distribute 100 tokens to the Investor automatically
  await tether.transfer(accounts[1], '100000000000000000') 
};

补充说明:执行Reward代币转账前需确认部署账号(即默认的accounts[0])持有对应数量的Reward代币,若Reward合约初始总供应量默认全部分配给部署账号则可直接执行,若合约有自定义初始分配规则,需提前确认部署账号余额充足避免交易回滚。

内容的提问来源于stack exchange,提问作者Jeffery Oke-Samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 13:57:08