cats.data.State Scala Examples
The following examples show how to use cats.data.State.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: AccountMergeResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.NativeAmount import stellar.sdk.model.xdr.{Decode, Encode} sealed abstract class AccountMergeResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 8) object AccountMergeResult extends Decode { val decode: State[Seq[Byte], AccountMergeResult] = int.flatMap { case 0 => long.map(NativeAmount).map(AccountMergeSuccess) case -1 => State.pure(AccountMergeMalformed) case -2 => State.pure(AccountMergeNoAccount) case -3 => State.pure(AccountMergeImmutable) case -4 => State.pure(AccountMergeHasSubEntries) case -5 => State.pure(AccountMergeSeqNumTooFar) case -6 => State.pure(AccountMergeDestinationFull) } } case object AccountMergeDestinationFull extends AccountMergeResult(-6)
Example 2
Source File: DerivedLawsSuite.scala From meow-mtl with MIT License | 5 votes |
package com.olegpy.meow.derivations import cats.{ApplicativeError, Eq, MonadError} import cats.data.State import cats.instances.all._ import cats.mtl._ import minitest._ import minitest.laws.Checkers import org.typelevel.discipline.Laws import com.olegpy.meow.hierarchy._ import cats.mtl.instances.all._ import cats.mtl.laws.discipline._ import cats.laws.discipline._ import cats.laws.discipline.arbitrary._ import cats.laws.discipline.eq._ import cats.laws.discipline.DeprecatedEqInstances._ object DerivedLawsSuite extends SimpleTestSuite with Checkers { private def checkAll(name: String)(ruleSet: Laws#RuleSet) = { for ((id, prop) <- ruleSet.all.properties) test(name + "." + id) { check(prop) } } type Data = (Long, Int) checkAll("MonadState") { type M[A] = State[Data, A] def derive[F[_]](implicit MS: MonadState[F, Data]): MonadState[F, Int] = implicitly implicit def eqState[A: Eq]: Eq[M[A]] = Eq.by(_.run((0L, 0))) MonadStateTests(derive[M]).monadState[Int] } checkAll("ApplicativeLocal") { type M[A] = Data => A def derive[F[_]](implicit MS: ApplicativeLocal[F, Data]): ApplicativeLocal[F, Int] = implicitly ApplicativeLocalTests(derive[M]).applicativeLocal[Int, String] } // checkAll("ApplicativeAsk") { // type M[A] = Data => A // def derive[F[_]](implicit MS: ApplicativeAsk[F, Data]): ApplicativeAsk[F, Int] = // implicitly // // ApplicativeAskTests(derive[M]).applicativeAsk[Int] // } type DataC = Either[String, Either[Int, Long]] checkAll("MonadError") { type M[A] = Either[DataC, A] def derive[F[_]](implicit MS: MonadError[F, DataC]): MonadError[F, Long] = implicitly MonadErrorTests(derive[M]).monadError[Int, Long, String] } checkAll("ApplicativeError") { type M[A] = Either[DataC, A] def derive[F[_]](implicit MS: ApplicativeError[F, DataC]): ApplicativeError[F, Long] = implicitly ApplicativeErrorTests(derive[M]).applicativeError[Int, Long, String] } checkAll("ApplicativeHandle") { type M[A] = Either[DataC, A] def derive[F[_]](implicit MS: ApplicativeHandle[F, DataC]): ApplicativeHandle[F, Long] = implicitly ApplicativeHandleTests(derive[M]).applicativeHandle[Int] } }
Example 3
Source File: Void.scala From skunk with MIT License | 5 votes |
// Copyright (c) 2018-2020 by Rob Norris // This software is licensed under the MIT License (MIT). // For more information see LICENSE or https://opensource.org/licenses/MIT package skunk import skunk.data.Type import cats.data.State import cats.implicits._ case object Void extends Void { val codec: Codec[Void] = new Codec[Void] { override def encode(a: Void): List[Option[String]] = Nil override def decode(index: Int, ss: List[Option[String]]): Either[Decoder.Error, Void.type ] = ss match { case Nil => Void.asRight case _ => Left(Decoder.Error(index, 0, s"Expected no values, found $ss")) } override val types: List[Type] = Nil override val sql: State[Int, String] = "".pure[State[Int, ?]] } }
Example 4
Source File: FocusedRef.scala From tofu with Apache License 2.0 | 5 votes |
package tofu.concurrent.impl import cats.Functor import cats.data.State import cats.effect.concurrent.Ref import tofu.optics.Contains import cats.syntax.functor._ final case class FocusedRef[F[_]: Functor, A, B](ref: Ref[F, A], focus: Contains[A, B]) extends Ref[F, B] { private def focusedMod[X](f: B => (B, X))(a: A): (A, X) = { val (next, res) = f(focus.extract(a)) focus.set(a, next) -> res } def get: F[B] = ref.get.map(focus.extract) def set(b: B): F[Unit] = ref.update(a => focus.set(a, b)) def update(f: B => B): F[Unit] = ref.update(focus.update(_, f)) def modify[X](f: B => (B, X)): F[X] = ref.modify(focusedMod(f)) def modifyState[X](state: State[B, X]): F[X] = ref.modifyState(focus.focusState(state)) def tryUpdate(f: B => B): F[Boolean] = ref.tryUpdate(focus.update(_, f)) def tryModify[X](f: B => (B, X)): F[Option[X]] = ref.tryModify(focusedMod(f)) def tryModifyState[X](state: State[B, X]): F[Option[X]] = ref.tryModifyState(focus.focusState(state)) def access: F[(B, B => F[Boolean])] = ref.access.map { case (a, update) => (focus.extract(a), b => update(focus.set(a, b))) } }
Example 5
Source File: package.scala From morpheus with Apache License 2.0 | 5 votes |
package org.opencypher.okapi.ir import cats.data.State import org.atnos.eff._ import org.atnos.eff.all._ import org.atnos.eff.syntax.all._ import org.opencypher.okapi.api.schema.PropertyGraphSchema import org.opencypher.okapi.api.types.{CTNode, CTRelationship, CypherType} import org.opencypher.okapi.impl.exception.IllegalArgumentException package object impl { type _mayFail[R] = MayFail |= R type _hasContext[R] = HasContext |= R type MayFail[A] = Either[IRBuilderError, A] type HasContext[A] = State[IRBuilderContext, A] type IRBuilderStack[A] = Fx.fx2[MayFail, HasContext] implicit final class RichIRBuilderStack[A](val program: Eff[IRBuilderStack[A], A]) { def run(context: IRBuilderContext): Either[IRBuilderError, (A, IRBuilderContext)] = { val stateRun = program.runState(context) val errorRun = stateRun.runEither[IRBuilderError] errorRun.run } } def error[R: _mayFail : _hasContext, A](err: IRBuilderError)(v: A): Eff[R, A] = left[R, IRBuilderError, BlockRegistry](err) >> pure(v) implicit final class RichSchema(schema: PropertyGraphSchema) { def forElementType(cypherType: CypherType): PropertyGraphSchema = cypherType match { case CTNode(labels, _) => schema.forNode(labels) case r: CTRelationship => schema.forRelationship(r) case x => throw IllegalArgumentException("element type", x) } def addLabelsToCombo(labels: Set[String], combo: Set[String]): PropertyGraphSchema = { val labelsWithAddition = combo ++ labels schema .dropPropertiesFor(combo) .withNodePropertyKeys(labelsWithAddition, schema.nodePropertyKeys(combo)) } def addPropertyToElement(propertyKey: String, propertyType: CypherType, elementType: CypherType): PropertyGraphSchema = { elementType match { case CTNode(labels, _) => val allRelevantLabelCombinations = schema.combinationsFor(labels) val property = if (allRelevantLabelCombinations.size == 1) propertyType else propertyType.nullable allRelevantLabelCombinations.foldLeft(schema) { case (innerCurrentSchema, combo) => val updatedPropertyKeys = innerCurrentSchema.nodePropertyKeysForCombinations(Set(combo)).updated(propertyKey, property) innerCurrentSchema.withOverwrittenNodePropertyKeys(combo, updatedPropertyKeys) } case CTRelationship(types, _) => val typesToUpdate = if (types.isEmpty) schema.relationshipTypes else types typesToUpdate.foldLeft(schema) { case (innerCurrentSchema, relType) => val updatedPropertyKeys = innerCurrentSchema.relationshipPropertyKeys(relType).updated(propertyKey, propertyType) innerCurrentSchema.withOverwrittenRelationshipPropertyKeys(relType, updatedPropertyKeys) } case other => throw IllegalArgumentException("node or relationship to set a property on", other) } } } }
Example 6
Source File: StateEffectPage.scala From eff with MIT License | 5 votes |
package org.atnos.site package lib object StateEffectPage extends UserGuidePage { def is = "State".title ^ s2""" A `State` effect can be seen as the combination of both a `Reader` and a `Writer` with these operations: - `get` get the current state - `put` set a new state Let's see an example showing that we can also use tags to track different states at the same time:${snippet{ import cats.data._ import org.atnos.eff._, all._, syntax.all._ type S1[A] = State[Int, A] type S2[A] = State[String, A] type S = Fx.fx2[S1, S2] val swapVariables: Eff[S, String] = for { v1 <- get[S, Int] v2 <- get[S, String] _ <- put[S, Int](v2.size) _ <- put[S, String](v1.toString) w1 <- get[S, Int] w2 <- get[S, String] } yield "initial: "+(v1, v2).toString+", final: "+(w1, w2).toString swapVariables.evalState(10).evalState("hello").run }.eval} In the example above we have used an `eval` method to get the `A` in `Eff[R, A]` but it is also possible to get both the value and the state with `run` or only the state with `exec`. Instead of tagging state effects it is also possible to transform a State effect acting on a "small" state into a State effect acting on a "bigger" state:${snippet{ import org.atnos.eff._, all._, syntax.all._ import cats.data.State type Count[A] = State[Int, A] type Sum[A] = State[Int, A] type Mean[A] = State[(Int, Int), A] type S1 = Fx.fx1[Count] type S2 = Fx.fx1[Sum] type S = Fx.fx1[Mean] def count(list: List[Int]): Eff[S1, String] = for { _ <- put(list.size) } yield s"there are ${list.size} values" def sum(list: List[Int]): Eff[S2, String] = { val s = if (list.isEmpty) 0 else list.sum for { _ <- put(s) } yield s"the sum is $s" } def mean(list: List[Int]): Eff[S, String] = for { m1 <- count(list).lensState((_:(Int, Int))._1, (s: (Int,Int), i: Int) => (i, s._2)) m2 <- sum(list).lensState((_:(Int, Int))._2, (s: (Int, Int), i: Int) => (s._1, i)) } yield m1+"\n"+m2 mean(List(1, 2, 3)).runState((0, 0)).run }.eval} """ }
Example 7
Source File: AllowTrustResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class AllowTrustResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 7) object AllowTrustResult extends Decode { val decode: State[Seq[Byte], AllowTrustResult] = int.map { case 0 => AllowTrustSuccess case -1 => AllowTrustMalformed case -2 => AllowTrustNoTrustLine case -3 => AllowTrustNotRequired case -4 => AllowTrustCannotRevoke case -5 => AllowTrustSelfNotAllowed } } case object AllowTrustSelfNotAllowed extends AllowTrustResult(-5)
Example 8
Source File: SetOptionsResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class SetOptionsResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 5) object SetOptionsResult extends Decode { val decode: State[Seq[Byte], SetOptionsResult] = int.map { case 0 => SetOptionsSuccess case -1 => SetOptionsLowReserve case -2 => SetOptionsTooManySigners case -3 => SetOptionsBadFlags case -4 => SetOptionsInvalidInflation case -5 => SetOptionsCannotChange case -6 => SetOptionsUnknownFlag case -7 => SetOptionsThresholdOutOfRange case -8 => SetOptionsBadSigner case -9 => SetOptionsInvalidHomeDomain } } case object SetOptionsInvalidHomeDomain extends SetOptionsResult(-9)
Example 9
Source File: CreatePassiveOfferResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class CreatePassiveSellOfferResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 4) object CreatePassiveSellOfferResult extends Decode { val decode: State[Seq[Byte], CreatePassiveSellOfferResult] = int.map { case 0 => CreatePassiveSellOfferSuccess case -1 => CreatePassiveSellOfferMalformed case -2 => CreatePassiveSellOfferSellNoTrust case -3 => CreatePassiveSellOfferBuyNoTrust case -4 => CreatePassiveSellOfferSellNoAuth case -5 => CreatePassiveSellOfferBuyNoAuth case -6 => CreatePassiveSellOfferLineFull case -7 => CreatePassiveSellOfferUnderfunded case -8 => CreatePassiveSellOfferCrossSelf case -9 => CreatePassiveSellOfferSellNoIssuer case -10 => CreatePassiveSellOfferBuyNoIssuer case -11 => UpdatePassiveOfferIdNotFound case -12 => CreatePassiveSellOfferLowReserve } } case object CreatePassiveSellOfferLowReserve extends CreatePassiveSellOfferResult(-12)
Example 10
Source File: ManageDataResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class ManageDataResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 10) object ManageDataResult extends Decode { val decode: State[Seq[Byte], ManageDataResult] = int.map { case 0 => ManageDataSuccess case -1 => ManageDataNotSupportedYet case -2 => DeleteDataNameNotFound case -3 => AddDataLowReserve case -4 => AddDataInvalidName } } case object AddDataInvalidName extends ManageDataResult(-4)
Example 11
Source File: CreateAccountResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class CreateAccountResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 0) object CreateAccountResult extends Decode { val decode: State[Seq[Byte], CreateAccountResult] = int.map { case 0 => CreateAccountSuccess case -1 => CreateAccountMalformed case -2 => CreateAccountUnderfunded case -3 => CreateAccountLowReserve case -4 => CreateAccountAlreadyExists } } case object CreateAccountAlreadyExists extends CreateAccountResult(-4)
Example 12
Source File: ManageOfferResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.ledger.OfferEntry import stellar.sdk.model.xdr.{Decode, Encode} sealed abstract class ManageOfferResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 3) object ManageOfferResult extends Decode { val decode: State[Seq[Byte], ManageOfferResult] = int.flatMap { case 0 => for { claims <- arr(OfferClaim.decode) entry <- switch[Option[OfferEntry]]( OfferEntry.decode.map(Some(_: OfferEntry)), OfferEntry.decode.map(Some(_: OfferEntry)), State.pure(Option.empty[OfferEntry]) ) } yield ManageOfferSuccess(claims, entry) case -1 => State.pure(ManageOfferMalformed) case -2 => State.pure(ManageOfferSellNoTrust) case -3 => State.pure(ManageOfferBuyNoTrust) case -4 => State.pure(ManageOfferSellNoAuth) case -5 => State.pure(ManageOfferBuyNoAuth) case -6 => State.pure(ManageOfferLineFull) case -7 => State.pure(ManageOfferUnderfunded) case -8 => State.pure(ManageOfferCrossSelf) case -9 => State.pure(ManageOfferSellNoIssuer) case -10 => State.pure(ManageOfferBuyNoIssuer) case -11 => State.pure(UpdateOfferIdNotFound) case -12 => State.pure(ManageOfferLowReserve) } } case object ManageOfferLowReserve extends ManageOfferResult(-12)
Example 13
Source File: InflationResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.NativeAmount import stellar.sdk.model.xdr.{Decode, Encodable, Encode} import stellar.sdk.{KeyPair, PublicKey} sealed abstract class InflationResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 9) object InflationResult extends Decode { val decode: State[Seq[Byte], InflationResult] = int.flatMap { case 0 => arr(InflationPayout.decode).map(InflationSuccess) case -1 => State.pure(InflationNotDue) } } case object InflationNotDue extends InflationResult(-1) case class InflationPayout(recipient: PublicKey, amount: NativeAmount) extends Encodable { def encode: LazyList[Byte] = recipient.encode ++ Encode.long(amount.units) } object InflationPayout extends Decode { val decode: State[Seq[Byte], InflationPayout] = for { recipient <- KeyPair.decode units <- long } yield InflationPayout(recipient, NativeAmount(units)) }
Example 14
Source File: OfferClaim.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.Amount import stellar.sdk.model.xdr.{Decode, Encodable, Encode} import stellar.sdk.{KeyPair, PublicKey} case class OfferClaim(seller: PublicKey, offerId: Long, sold: Amount, bought: Amount) extends Encodable { def encode: LazyList[Byte] = seller.encode ++ Encode.long(offerId) ++ sold.encode ++ bought.encode } object OfferClaim extends Decode { val decode: State[Seq[Byte], OfferClaim] = for { seller <- KeyPair.decode offerId <- long sold <- Amount.decode bought <- Amount.decode } yield OfferClaim(seller, offerId, sold, bought) }
Example 15
Source File: EntityParser.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.domain.bytes.deser import cats.data.State import com.google.common.primitives.{Ints, Longs} import com.wavesplatform.dex.domain.account.PublicKey import com.wavesplatform.dex.domain.asset.Asset import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves} import com.wavesplatform.dex.domain.bytes.{ByteStr, deser} import com.wavesplatform.dex.domain.crypto.{KeyLength, Proofs, SignatureLength} import com.wavesplatform.dex.domain.utils._ import scala.util.Try trait EntityParser[E] { import EntityParser._ protected def read[R: Stateful]: Stateful[R] = implicitly private[domain] def statefulParse: Stateful[E] def parseBytes(bytes: Array[Byte]): Try[E] = Try { statefulParse.runA(S(0, bytes)).value } } object EntityParser { private[domain] final case class S(offset: Int, bytes: Array[Byte]) type Stateful[T] = State[S, T] type Signature = ByteStr private def standardRead[R](f: Array[Byte] => R, size: Int): Stateful[R] = State[S, R] { s => s.copy(offset = s.offset + size) -> f(s.bytes.slice(s.offset, s.offset + size)) } implicit val readByte: Stateful[Byte] = standardRead(_.head, 1) implicit val readInt: Stateful[Int] = standardRead(Ints.fromByteArray, 4) implicit val readLong: Stateful[Long] = standardRead(Longs.fromByteArray, 8) implicit val readPublicKey: Stateful[PublicKey] = standardRead(PublicKey.apply, KeyLength) implicit val readSignature: Stateful[Signature] = standardRead(ByteStr.apply, SignatureLength) implicit val readProofs: Stateful[Proofs] = State[S, Proofs] { s => val (proofs, length) = Proofs.fromBytes(s.bytes drop s.offset).explicitGet() s.copy(offset = s.offset + length) -> proofs } implicit val readAsset: Stateful[Asset] = State[S, Asset] { s => val (maybeByteArr, resultOffset) = deser.parseByteArrayOption(s.bytes, s.offset, Asset.AssetIdLength) s.copy(offset = resultOffset) -> maybeByteArr.fold[Asset](Waves)(arr => IssuedAsset(ByteStr(arr))) } }
Example 16
Source File: PathPaymentResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.{Amount, Asset} import stellar.sdk.{KeyPair, PublicKey} import stellar.sdk.model.xdr.{Decode, Encode} sealed abstract class PathPaymentResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 2) object PathPaymentResult extends Decode { val decode: State[Seq[Byte], PathPaymentResult] = int.flatMap { case 0 => arr(OfferClaim.decode).flatMap { claims => KeyPair.decode.flatMap { destination => Amount.decode.map(PathPaymentSuccess(claims, destination, _)) } } case -1 => State.pure(PathPaymentMalformed) case -2 => State.pure(PathPaymentUnderfunded) case -3 => State.pure(PathPaymentSourceNoTrust) case -4 => State.pure(PathPaymentSourceNotAuthorised) case -5 => State.pure(PathPaymentNoDestination) case -6 => State.pure(PathPaymentDestinationNoTrust) case -7 => State.pure(PathPaymentDestinationNotAuthorised) case -8 => State.pure(PathPaymentDestinationLineFull) case -9 => Asset.decode.map(PathPaymentNoIssuer) case -10 => State.pure(PathPaymentTooFewOffers) case -11 => State.pure(PathPaymentOfferCrossesSelf) case -12 => State.pure(PathPaymentSendMaxExceeded) } } case object PathPaymentSendMaxExceeded extends PathPaymentResult(-12)
Example 17
Source File: PaymentResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class PaymentResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 1) object PaymentResult extends Decode { val decode: State[Seq[Byte], PaymentResult] = int.map { case 0 => PaymentSuccess case -1 => PaymentMalformed case -2 => PaymentUnderfunded case -3 => PaymentSourceNoTrust case -4 => PaymentSourceNotAuthorised case -5 => PaymentNoDestination case -6 => PaymentDestinationNoTrust case -7 => PaymentDestinationNotAuthorised case -8 => PaymentDestinationLineFull case -9 => PaymentNoIssuer } } case object PaymentNoIssuer extends PaymentResult(-9)
Example 18
Source File: ChangeTrustResult.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.result import cats.data.State import stellar.sdk.model.xdr.Decode sealed abstract class ChangeTrustResult(val opResultCode: Int) extends ProcessedOperationResult(opCode = 6) object ChangeTrustResult extends Decode { val decode: State[Seq[Byte], ChangeTrustResult] = int.map { case 0 => ChangeTrustSuccess case -1 => ChangeTrustMalformed case -2 => ChangeTrustNoIssuer case -3 => ChangeTrustInvalidLimit case -4 => ChangeTrustLowReserve case -5 => ChangeTrustSelfNotAllowed } } case object ChangeTrustSelfNotAllowed extends ChangeTrustResult(-5)
Example 19
Source File: Asset.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model import cats.data.State import stellar.sdk.model.xdr.{Decode, Encodable, Encode} import stellar.sdk.util.ByteArrays._ import stellar.sdk.{KeyPair, PublicKeyOps} sealed trait Asset extends Encodable { val code: String } object Asset extends Decode { def apply(code: String, issuer: PublicKeyOps): NonNativeAsset = { require(code.matches("[a-zA-Z0-9?]+"), s"Asset code $code does not match [a-zA-Z0-9]+") if (code.length <= 4) IssuedAsset4.of(code, issuer) else IssuedAsset12.of(code, issuer) } val decode: State[Seq[Byte], Asset] = int.flatMap { case 0 => State.pure(NativeAsset) case 1 => IssuedAsset4.decode.map(x => x: Asset) case 2 => IssuedAsset12.decode.map(x => x: Asset) } } case object NativeAsset extends Asset { val code: String = "XLM" override def encode: LazyList[Byte] = Encode.int(0) } sealed trait NonNativeAsset extends Asset { val code: String val issuer: PublicKeyOps val typeString: String override def toString: String = s"${issuer.accountId}:$code" } case class IssuedAsset12 private (code: String, issuer: PublicKeyOps) extends NonNativeAsset { assert(code.length >= 5 && code.length <= 12, s"Asset's code '$code' should have length between 5 & 12 inclusive") override val typeString = "credit_alphanum12" def encode: LazyList[Byte] = { val codeBytes = paddedByteArray(code, 12) Encode.int(2) ++ Encode.bytes(12, codeBytes) ++ issuer.encode } } object IssuedAsset12 extends Decode { def of(code: String, keyPair: PublicKeyOps): IssuedAsset12 = IssuedAsset12(code, keyPair.asPublicKey) def decode: State[Seq[Byte], IssuedAsset12] = for { bs <- bytes(12) issuer <- KeyPair.decode code = paddedByteArrayToString(bs.toArray) } yield IssuedAsset12(code, issuer) }
Example 20
Source File: Decode.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.xdr import java.io.EOFException import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.time.Instant import cats.Eval import cats.data.{IndexedStateT, State} import com.typesafe.scalalogging.LazyLogging import scala.util.Try trait Decode extends LazyLogging { private def decode[T](bs: Seq[Byte], len: Int)(decoder: Seq[Byte] => T): (Seq[Byte], T) = { if (bs.length < len) throw new EOFException("Insufficient data remains to parse.") val t = decoder(bs.take(len)) logger.trace(s"Dropping {} to make {}", len, t) bs.drop(len) -> t } val int: State[Seq[Byte], Int] = State[Seq[Byte], Int] { bs => decode(bs, 4) { in => ByteBuffer.wrap(in.toArray).getInt } } val long: State[Seq[Byte], Long] = State[Seq[Byte], Long] { bs => decode(bs, 8) { in => ByteBuffer.wrap(in.toArray).getLong } } val instant: State[Seq[Byte], Instant] = long.map(Instant.ofEpochSecond) val bool: State[Seq[Byte], Boolean] = int.map(_ == 1) def bytes(len: Int): State[Seq[Byte], Seq[Byte]] = State[Seq[Byte], Seq[Byte]] { bs => decode(bs, len) { _.take(len) } } val bytes: State[Seq[Byte], Seq[Byte]] = for { len <- int bs <- bytes(len) } yield bs def padded(multipleOf: Int = 4): State[Seq[Byte], Seq[Byte]] = for { len <- int bs <- bytes(len) _ <- bytes((multipleOf - (len % multipleOf)) % multipleOf) } yield bs val string: State[Seq[Byte], String] = padded().map(_.toArray).map(new String(_, StandardCharsets.UTF_8)) def switch[T](zero: State[Seq[Byte], T], others: State[Seq[Byte], T]*): IndexedStateT[Eval, Seq[Byte], Seq[Byte], T] = int.flatMap { case 0 => zero case n => Try(others(n - 1)).getOrElse { throw new IllegalArgumentException(s"No parser defined for discriminant $n") } } // TODO (jem) - All switches should use this instead and Discriminators should be held in the parent (switcher not switchee). def switchInt[T](zero: State[Seq[Byte], T], others: State[Seq[Byte], T]*): State[Seq[Byte], (T, Int)] = int.flatMap { case 0 => zero.map(_ -> 0) case n => Try(others(n - 1).map(_ -> n)).getOrElse { throw new IllegalArgumentException(s"No parser defined for discriminant $n") } } def opt[T](parseT: State[Seq[Byte], T]): State[Seq[Byte], Option[T]] = bool.flatMap { case true => parseT.map(Some(_)) case false => State.pure(None) } def arr[T](parseT: State[Seq[Byte], T]): State[Seq[Byte], Seq[T]] = int.flatMap(seq(_, parseT)) // $COVERAGE-OFF$ // For debugging XDR only. def log[T](t: T): State[Seq[Byte], Unit] = State[Seq[Byte], Unit] { bs => logger.debug("{}\n", t) bs -> () } // $COVERAGE-ON$ def seq[T](qty: Int, parseT: State[Seq[Byte], T]): State[Seq[Byte], Seq[T]] = { (0 until qty).foldLeft(State.pure[Seq[Byte], Seq[T]](Seq.empty[T])) { case (state, _) => for { ts <- state t <- parseT } yield ts :+ t } } def drop[T](parse: State[Seq[Byte], _])(t: T): State[Seq[Byte], T] = for { _ <- parse } yield t def widen[A, W, O <: W](s: State[A, O]): State[A, W] = s.map(w => w: W) }
Example 21
Source File: LedgerKey.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.ledger import cats.data.State import stellar.sdk.model.xdr.{Decode, Encodable, Encode} import stellar.sdk.model.{Asset, NonNativeAsset} import stellar.sdk.{KeyPair, PublicKeyOps} sealed trait LedgerKey extends Encodable object LedgerKey extends Decode { val decode: State[Seq[Byte], LedgerKey] = switch[LedgerKey]( widen(AccountKey.decode), widen(TrustLineKey.decode), widen(OfferKey.decode), widen(DataKey.decode) ) } case class AccountKey(account: PublicKeyOps) extends LedgerKey { override def encode: LazyList[Byte] = Encode.int(0) ++ account.encode } object AccountKey extends Decode { val decode: State[Seq[Byte], AccountKey] = KeyPair.decode.map(AccountKey(_)) } case class TrustLineKey(account: PublicKeyOps, asset: NonNativeAsset) extends LedgerKey { override def encode: LazyList[Byte] = Encode.int(1) ++ account.encode ++ asset.encode } object TrustLineKey extends Decode { val decode: State[Seq[Byte], TrustLineKey] = for { account <- KeyPair.decode asset <- Asset.decode.map(_.asInstanceOf[NonNativeAsset]) } yield TrustLineKey(account, asset) } case class OfferKey(account: PublicKeyOps, offerId: Long) extends LedgerKey { override def encode: LazyList[Byte] = Encode.int(2) ++ account.encode ++ Encode.long(offerId) } object OfferKey extends Decode { val decode: State[Seq[Byte], OfferKey] = for { account <- KeyPair.decode offerId <- long } yield OfferKey(account, offerId) } case class DataKey(account: PublicKeyOps, name: String) extends LedgerKey { override def encode: LazyList[Byte] = Encode.int(3) ++ account.encode ++ Encode.string(name) } object DataKey extends Decode { val decode: State[Seq[Byte], DataKey] = for { account <- KeyPair.decode name <- string } yield DataKey(account, name) }
Example 22
Source File: Liabilities.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.ledger import cats.data.State import stellar.sdk.model.xdr.{Decode, Encodable} import stellar.sdk.model.xdr.Encode._ case class Liabilities(buying: Long, selling: Long) extends Encodable { override def encode: LazyList[Byte] = long(buying) ++ long(selling) ++ int(0) } object Liabilities extends Decode { val decode: State[Seq[Byte], Liabilities] = for { buying <- long selling <- long _ <- int } yield Liabilities(buying, selling) }
Example 23
Source File: LedgerEntryChanges.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.ledger import cats.data.State import stellar.sdk.model.ledger.TransactionLedgerEntries.arr import stellar.sdk.model.xdr.{Decode, Encodable, Encode} import stellar.sdk.util.ByteArrays sealed trait LedgerEntryChange extends Encodable case class LedgerEntryCreate(entry: LedgerEntry) extends LedgerEntryChange { override def encode: LazyList[Byte] = Encode.int(0) ++ entry.encode ++ Encode.int(0) } case class LedgerEntryUpdate(entry: LedgerEntry) extends LedgerEntryChange { override def encode: LazyList[Byte] = Encode.int(1) ++ entry.encode ++ Encode.int(0) } case class LedgerEntryDelete(entry: LedgerKey) extends LedgerEntryChange { override def encode: LazyList[Byte] = Encode.int(2) ++ entry.encode } case class LedgerEntryState(entry: LedgerEntry) extends LedgerEntryChange { override def encode: LazyList[Byte] = Encode.int(3) ++ entry.encode ++ Encode.int(0) } object LedgerEntryChange extends Decode { val decode: State[Seq[Byte], LedgerEntryChange] = switch[LedgerEntryChange]( widen(LedgerEntry.decode.map(LedgerEntryCreate).flatMap(drop(int))), widen(LedgerEntry.decode.map(LedgerEntryUpdate).flatMap(drop(int))), widen(LedgerKey.decode.map(LedgerEntryDelete)), widen(LedgerEntry.decode.map(LedgerEntryState).flatMap(drop(int))) ) } object LedgerEntryChanges { def decodeXDR(base64: String): Seq[LedgerEntryChange] = arr(LedgerEntryChange.decode).run(ByteArrays.base64(base64).toIndexedSeq).value._2 }
Example 24
Source File: TransactionLedgerEntries.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model.ledger import cats.data.State import stellar.sdk.model.xdr.{Decode, Encodable, Encode, Encoded} import stellar.sdk.util.ByteArrays case class TransactionLedgerEntries(txnLevelChanges: Option[(Option[Seq[LedgerEntryChange]], Seq[LedgerEntryChange])], operationLevelChanges: Seq[Seq[LedgerEntryChange]]) extends Encodable { val txnLevelChangesBefore: Option[Seq[LedgerEntryChange]] = txnLevelChanges.flatMap(_._1) val txnLevelChangesAfter: Option[Seq[LedgerEntryChange]] = txnLevelChanges.map(_._2) override def encode: LazyList[Byte] = txnLevelChanges match { case Some((Some(before), after)) => encode2(before, after) case Some((_, after)) => encode1(after) case _ => encode0 } private def encode0: LazyList[Byte] = Encode.int(0) ++ Encode.arr(operationLevelChanges.map(Encode.arr(_)).map(Encoded)) private def encode1(txnLevel: Seq[LedgerEntryChange]): LazyList[Byte] = Encode.int(1) ++ Encode.arr(txnLevel) ++ Encode.arr(operationLevelChanges.map(Encode.arr(_)).map(Encoded)) private def encode2(before: Seq[LedgerEntryChange], after: Seq[LedgerEntryChange]): LazyList[Byte] = Encode.int(2) ++ Encode.arr(before) ++ Encode.arr(operationLevelChanges.map(Encode.arr(_)).map(Encoded)) ++ Encode.arr(after) } object TransactionLedgerEntries extends Decode { def decodeXDR(base64: String): TransactionLedgerEntries = decode.run(ByteArrays.base64(base64).toIndexedSeq).value._2 private val decodeV0: State[Seq[Byte], TransactionLedgerEntries] = for { ops <- arr(arr(LedgerEntryChange.decode)) } yield TransactionLedgerEntries(None, ops) private val decodeV1: State[Seq[Byte], TransactionLedgerEntries] = for { txnLevelChanges <- arr(LedgerEntryChange.decode) ops <- arr(arr(LedgerEntryChange.decode)) } yield TransactionLedgerEntries(Some(None, txnLevelChanges), ops) private val decodeV2: State[Seq[Byte], TransactionLedgerEntries] = for { txnLevelChangesBefore <- arr(LedgerEntryChange.decode) ops <- arr(arr(LedgerEntryChange.decode)) txnLevelChangesAfter <- arr(LedgerEntryChange.decode) } yield TransactionLedgerEntries(Some(Some(txnLevelChangesBefore), txnLevelChangesAfter), ops) val decode: State[Seq[Byte], TransactionLedgerEntries] = switch(decodeV0, decodeV1, decodeV2) }
Example 25
Source File: Memo.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model import java.nio.charset.StandardCharsets.UTF_8 import cats.data.State import stellar.sdk.util.ByteArrays._ import stellar.sdk.model.xdr.{Decode, Encode} import scala.util.Try sealed trait Memo { def encode: LazyList[Byte] } object Memo extends Decode { def decode: State[Seq[Byte], Memo] = switch( State.pure(NoMemo), string.map(MemoText), long.map(MemoId), bytes.map(_.toIndexedSeq).map(MemoHash(_)), bytes.map(_.toIndexedSeq).map(MemoReturnHash(_)) ) } case object NoMemo extends Memo { override def encode: LazyList[Byte] = Encode.int(0) } case class MemoText(text: String) extends Memo { val Length = 28 val bytes = text.getBytes(UTF_8) assert(bytes.length <= Length, s"Text exceeded limit (${bytes.length}/$Length bytes)") override def encode: LazyList[Byte] = Encode.int(1) ++ Encode.string(text) } case class MemoId(id: Long) extends Memo { override def encode: LazyList[Byte] = Encode.int(2) ++ Encode.long(id) def unsignedId: BigInt = BigInt(java.lang.Long.toUnsignedString(id)) override def toString = s"MemoId(${unsignedId.toString()})" } sealed trait MemoWithHash extends Memo { val Length = 32 val bs: Seq[Byte] val bytes: Array[Byte] = paddedByteArray(bs.toArray, Length) def hex: String = bytesToHex(bytes) def hexTrim: String = bytesToHex(bs) } case class MemoHash(bs: Seq[Byte]) extends MemoWithHash { assert(bs.length <= Length, s"Hash exceeded limit (${bytes.length}/$Length bytes)") override def encode: LazyList[Byte] = Encode.int(3) ++ Encode.bytes(bs) } object MemoHash { def from(hex: String): Try[MemoHash] = Try(MemoHash(hexToBytes(hex))) } case class MemoReturnHash(bs: Seq[Byte]) extends MemoWithHash { assert(bs.length <= Length, s"Hash exceeded limit (${bytes.length}/$Length bytes)") override def encode: LazyList[Byte] = Encode.int(4) ++ Encode.bytes(bs) } object MemoReturnHash { def from(hex: String) = Try(MemoReturnHash(hexToBytes(hex))) }
Example 26
Source File: Amount.scala From scala-stellar-sdk with Apache License 2.0 | 5 votes |
package stellar.sdk.model import java.math.{MathContext, RoundingMode} import java.util.Locale import cats.data.State import stellar.sdk.model.xdr.{Decode, Encodable, Encode} import scala.util.Try sealed trait Amount extends Encodable { val units: Long val asset: Asset def toDisplayUnits: String = "%.7f".formatLocal(Locale.ROOT, BigDecimal(units) / Amount.toIntegralFactor) def encode: LazyList[Byte] = asset.encode ++ Encode.long(units) } case class NativeAmount(units: Long) extends Amount { override val asset: Asset = NativeAsset override def toString: String = s"$toDisplayUnits XLM" } case class IssuedAmount(units: Long, asset: NonNativeAsset) extends Amount { override def toString: String = s"$toDisplayUnits $asset" } object Amount extends Decode { private val decimalPlaces = 7 private val toIntegralFactor = BigDecimal(math.pow(10, decimalPlaces)) def toBaseUnits(d: Double): Try[Long] = toBaseUnits(BigDecimal(d)) def toBaseUnits(s: String): Try[Long] = Try(BigDecimal(s)).flatMap(toBaseUnits) def toBaseUnits(bd: BigDecimal): Try[Long] = Try { (bd * toIntegralFactor.round(new MathContext(0, RoundingMode.DOWN))).toLongExact } def apply(units: Long, asset: Asset): Amount = { asset match { case NativeAsset => NativeAmount(units) case a: NonNativeAsset => IssuedAmount(units, a) } } def lumens(units: Double): NativeAmount = toBaseUnits(units).map(NativeAmount).getOrElse( throw new IllegalArgumentException(s"Too many digits in fractional portion of $units. Limit is $decimalPlaces") ) def decode: State[Seq[Byte], Amount] = for { asset <- Asset.decode units <- long } yield apply(units, asset) } object IssuedAmount { def decode: State[Seq[Byte], IssuedAmount] = Amount.decode.map(x => x.asInstanceOf[IssuedAmount]) }
Example 27
Source File: Optimize.scala From skeuomorph with Apache License 2.0 | 5 votes |
package higherkindness.skeuomorph.openapi import higherkindness.droste._ import cats.data.State import cats.implicits._ import scala.annotation.tailrec object Optimize { def namedTypesTrans[T](name: String): Trans[JsonSchemaF, JsonSchemaF, T] = Trans { case JsonSchemaF.ObjectF(_, _) => JsonSchemaF.reference[T](name) case JsonSchemaF.EnumF(_) => JsonSchemaF.reference[T](name) case other => other } def namedTypes[T: Basis[JsonSchemaF, ?]](name: String): T => T = scheme.cata(namedTypesTrans(name).algebra) type NestedTypesState[T, O] = State[(Map[String, T], Long), O] def nestedTypesTrans[T: Basis[JsonSchemaF, ?]]: TransM[NestedTypesState[T, ?], JsonSchemaF, JsonSchemaF, T] = TransM { case JsonSchemaF.ArrayF(x) if isNestedType(x) => extractNestedTypes("AnonymousObject", x).map { case (n, t) => JsonSchemaF.ArrayF(namedTypes(n).apply(t)) } case JsonSchemaF.ObjectF(fields, required) => fields .traverse[NestedTypesState[T, ?], JsonSchemaF.Property[T]] { case p if isNestedType(p.tpe) => extractNestedTypes(p.name.capitalize, p.tpe).map { //TODO Maybe we should normalize case (n, t) => p.copy(tpe = namedTypes[T](n).apply(t)) } case p => State.pure(p) } .map(JsonSchemaF.ObjectF(_, required)) case other => State.pure(other) } def nestedTypes[T: Basis[JsonSchemaF, ?]]: T => NestedTypesState[T, T] = scheme.anaM(nestedTypesTrans.coalgebra) private def isNestedType[T: Project[JsonSchemaF, ?]](t: T): Boolean = { import JsonSchemaF._ import higherkindness.droste.syntax.project.toProjectSyntaxOps t.project match { case ObjectF(properties, _) if properties.nonEmpty => true case EnumF(_) => true case _ => false } } private def extractNestedTypes[T: Basis[JsonSchemaF, ?]](name: String, tpe: T): NestedTypesState[T, (String, T)] = { def addType(items: (String, T)): NestedTypesState[T, Unit] = State.modify { case (x, y) => (x + items) -> y } def generateName(originalName: String, previousOccurrences: Long): String = originalName.capitalize + (if (previousOccurrences > 0) previousOccurrences.toString else "") @tailrec def findNameAndIndex(ix: Long, x: Map[String, _]): (String, Long) = { val n = generateName(name, ix) if (x.contains(n)) findNameAndIndex(ix + 1, x) else n -> ix } def findName: NestedTypesState[T, String] = State { case (x, i) => val (name, nextI) = findNameAndIndex(i, x) (x, nextI) -> name } for { newType <- nestedTypes.apply(tpe) newName <- findName _ <- addType(newName -> newType) } yield newName -> newType } }