我正在使用@polkadot-js设置一个Nuxt.js应用程序。当我用我的@polkadot/types请求自定义底层运行时模块时,我得到了这个错误Class constructor Struct cannot be invoked without 'new'。
这是一个具有官方设置的Nuxt.js应用程序。在过去,我曾尝试使用干净的Nuxt.js和Vue来设置它,但总是出现相同的错误。只有当我设置干净的NodeJS (使用或不使用typescript)或@polkadot react应用程序时,它才能正常工作。
我已经创建了一个repository来尝试一些其他方法。
接口调用:
class VecU32 extends Vector.with(u32) {}
class Kind extends Struct {
constructor(value) {
super({
stuff: VecU32
}, value);
}
}
const Alice = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY";
const provider = new WsProvider("ws://127.0.0.1:9944");
const typeRegistry = getTypeRegistry();
typeRegistry.register({ Kind });
const api = await ApiPromise.create(provider);
// With types providede in create function - works well
// types: {
// Kind: {
// stuff: "Vec<u32>"
// }
// }
const res = await api.query.template.kinds(Alice);
console.log(res);我期望结果输出为空(或一些值,取决于区块链中的内容),但实际输出的是错误Class constructor Struct cannot be invoked without 'new'。
发布于 2019-07-05 20:34:28
简短回答:
请执行以下操作,而不是此const typeRegistry = getTypeRegistry();:
const typeRegistry.register({
Kind: {
'stuff': 'Vec<u32>'
}
});较长的应答
当您调用typeRegistry.register({ Kind });时,您正在尝试将Typescript类注册为注册表中的自定义类型,但是您需要传递给API的类型注册表的类型与您的Typescript类型无关,这两者没有直接关联。
如果您要编写纯Javascript,则需要在Polkadot-JS API中注册您的自定义基板类型。
传递给API的类型用于解码和编码发送到底层节点和从底层节点接收的数据。它们符合SCALE编解码器,该编解码器也在基板核心Rust代码中实现。使用这些类型可以确保数据可以在不同的环境中以不同的语言正确地解压和编码。
你可以在这里阅读更多信息:https://substrate.dev/docs/en/overview/low-level-data-format
这些类型的Javascript表示在Polkadot-JS文档中被列为“编解码器类型”:https://polkadot.js.org/api/types/#codec-types
您在Polkadot-JS文档中找到的所有其他类型都是这些低级编解码器类型的扩展。
您需要传递给JS-API的是所有自定义底层模块的所有自定义类型,以便API知道如何对您的数据进行解压和编码,因此在本例中您声明的是here in Rust。
pub struct Kind {
stuff: Vec<u32>,
}在Javascript中需要像这样注册:
const typeRegistry.register({
Kind: {
'stuff': 'Vec<u32>'
}
});另一方面,你的 typescript 类型是为了确保你在前端用typescript编写的处理客户端的数据具有正确的类型。
它们只由Typescript使用,并且添加了额外的安全层,但类型本身并不需要与API进行通信。不过,您的数据绝对需要具有正确的格式,以防止错误。
您可以将https://www.npmjs.com/package/@polkadot/types看作是特定于底层/波尔卡多特的https://github.com/DefinitelyTyped/DefinitelyTyped版本
但是即使你没有使用Typescript,https://polkadot.js.org/api/types/仍然是你100%的首选参考。
https://stackoverflow.com/questions/56898273
复制相似问题