0

Trying to create a uniqueId in AS. I added this package npm install as-nanoid --save

The nanoid function from the install is as follows:

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
}

In my assembly index.ts file I have the following:

import { nanoid } from 'as-nanoid'

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

Using NEAR-SDK-AS When I initialize the contract after deploying it. near call $CONTRACT init --accountId $CONTRACT

I get the following error:

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

Any help here would be appreciated or if there is a simpler way of creating a uniqueId please share.

andy-dev
  • 113
  • 6

1 Answers1

2
function generateRandomDna(): string {
  let buf = math.randomBuffer(DNA_DIGITS);
  let b64 = base64.encode(buf);
  return b64;
}

Something like this, from the docs, with a variation using available Math if necessary.

What I do in my contracts, for now, is putting together the account name and block height:

const title = context.sender.substring(0, context.sender.lastIndexOf('.'))
this.id = title + '-' + context.blockIndex.toString()
Yassine S.
  • 1,061
  • 1
  • 13
  • 22
  • this is great, can you please share where in the docs I can see this? – andy-dev Oct 23 '21 at 23:04
  • I was thinking of just generating the UID in the front-end and pass it as a parameter when creating an instance of the class instead of automatically creating it in AS. Thoughts? – andy-dev Oct 23 '21 at 23:08
  • 1
    @andy-dev It shouldn't be a problem, but I would not rely on the front-end too much. That been said, the user can see parameters passed to the function before signing. – Yassine S. Oct 24 '21 at 15:59