diff --git a/server/app/com/xsn/explorer/models/values/Address.scala b/server/app/com/xsn/explorer/models/values/Address.scala new file mode 100644 index 0000000..efeec62 --- /dev/null +++ b/server/app/com/xsn/explorer/models/values/Address.scala @@ -0,0 +1,39 @@ +package com.xsn.explorer.models.values + +import com.alexitc.playsonify.models.WrappedString +import javax.xml.bind.DatatypeConverter +import play.api.libs.json._ + +import scala.util.Try + +class Address private (val string: String) extends AnyVal with WrappedString + +object Address { + + private val pattern = "^[a-zA-Z0-9]{34,64}$".r.pattern + + def from(string: String): Option[Address] = { + if (pattern.matcher(string).matches()) { + Some(new Address(string)) + } else { + None + } + } + + def fromHex(hex: String): Option[Address] = { + Try { DatatypeConverter.parseHexBinary(hex) } + .map { bytes => new String(bytes) } + .toOption + .flatMap(from) + } + + implicit val reads: Reads[Address] = Reads { json => + json.validate[String].flatMap { string => + from(string) + .map(JsSuccess.apply(_)) + .getOrElse { + JsError.apply("Invalid address") + } + } + } +} diff --git a/server/app/com/xsn/explorer/models/values/package.scala b/server/app/com/xsn/explorer/models/values/package.scala new file mode 100644 index 0000000..413a809 --- /dev/null +++ b/server/app/com/xsn/explorer/models/values/package.scala @@ -0,0 +1,8 @@ +package com.xsn.explorer.models + +/** + * Package dedicated to store value classes that are core to the project. + */ +package object values { + +}