Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Fixed Type for EVM Addresses #236

Open
Tracked by #177
bh2smith opened this issue Apr 12, 2023 · 2 comments
Open
Tracked by #177

Use Fixed Type for EVM Addresses #236

bh2smith opened this issue Apr 12, 2023 · 2 comments

Comments

@bh2smith
Copy link
Contributor

Some of our code is a bit brittle because of the loosely thrown around primitive strings. Some libraries use checksum addresses and others use lowercase. We should make this uniform across the project so to avoid these ugly little fixes.

This change is a bit ugly and is a result of having to "normalize" hex strings. We should probably find a global/universal solution to this problem instead of having to make conversions all the time.

Originally posted by @bh2smith in #231 (comment)

@bh2smith
Copy link
Contributor Author

An approach proposed by @tukantje on slack is as follows:

type Nominal<T extends string, K> = {
  _type: T
  value: K
}

type Address = Nominal<"Address", string>

const addressRegex = new RegExp("^0x[a-fA-F0-9]{40}$/")

function isAddressString(value: string) {
  return addressRegex.test(value)
}

function isAddress(nominal: Nominal<string, any>): nominal is Address {
  return isAddressString(nominal.value)
}

function makeAddress(text: string): Address {
  if (!isAddressString(text)) {
    // Could also return null, depends on your usecase.
    throw new Error(`Invalid text supplied: can't make an address out of ${text}`)
  }

  return Object.freeze({
    value: text,
    _type: "Address"
  })
}

const address = makeAddress("0x23233222"); // Expected to fail, not a valid address.

@bh2smith
Copy link
Contributor Author

Apparently also, this is "coming soon"

microsoft/TypeScript#41160

There is this cheeky trick (that isn't super useful).

type Address = `0x${Lowercase<string>}`

and ethers offers this method: https://docs.ethers.org/v6/api/address/#getAddress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant