【问题标题】:How to create a UID in AssemblyScript for a NEAR contract?如何在 AssemblyScript 中为 NEAR 合约创建 UID?
【发布时间】:2023-03-10 16:08:01
【问题描述】:

试图在 AS 中创建一个 uniqueId。 我添加了这个包 npm install as-nanoid --save

安装的 nanoid 函数如下:

let urlAlphabet = ['M','o','d','u','l','e','S','y','m','b','h','a','s','O','w','n','P','r','-','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','N','R','V','f','g','c','t','i','U','v','z','_','K','q','Y','T','J','k','L','x','p','Z','X','I','j','Q','W']

export function nanoid(length: number = 21): string {
  let id = ''
  for (let i = 0; i < length; i++) {
    id += urlAlphabet[i32(Math.floor(Math.random() * 64))]
  }
  return id
}

在我的程序集index.ts 文件中,我有以下内容:

import { nanoid } from 'as-nanoid'

@nearBindgen
class MyClass {
  public id: string
  constructor() {
    this.id = nanoid(8)
  }
}

使用NEAR-SDK-AS 当我在部署合同后初始化合同时。 near call $CONTRACT init --accountId $CONTRACT

我收到以下错误:

Error: {"index":0,"kind":{"ExecutionError":"Link Error: Error while importing \"env\".\"seed\": unknown import. Expected Function(FunctionType { params: [], results: [F64] })"}}

如有任何帮助,我们将不胜感激,或者如果有更简单的方法来创建 uniqueId,请分享。

【问题讨论】:

    标签: nearprotocol assemblyscript


    【解决方案1】:
    function generateRandomDna(): string {
      let buf = math.randomBuffer(DNA_DIGITS);
      let b64 = base64.encode(buf);
      return b64;
    }
    

    类似的东西,来自文档,如有必要,使用可用的Math 进行变体。

    我现在在合约中所做的是将账户名和区块高度放在一起:

    const title = context.sender.substring(0, context.sender.lastIndexOf('.'))
    this.id = title + '-' + context.blockIndex.toString()
    

    【讨论】:

    • 这太好了,你能分享一下我在文档中哪里可以看到这个吗?
    • 我在想只是在前端生成UID并在创建类的实例时将其作为参数传递,而不是在AS中自动创建它。想法?
    • @andy-dev 应该没问题,但我不会过分依赖前端。也就是说,用户可以在签名之前看到传递给函数的参数。
    猜你喜欢
    • 2022-07-02
    • 2022-07-14
    • 2020-01-13
    • 2021-12-01
    • 2021-06-13
    • 2021-01-14
    • 2021-07-23
    • 2018-10-23
    • 2021-04-16
    相关资源
    最近更新 更多