nim-nitro/nitro/protocol/outcome.nim

77 lines
2.1 KiB
Nim
Raw Normal View History

import pkg/nimcrypto
import ../basics
import ./abi
{.push raises: [].}
2021-03-03 10:30:07 +01:00
export basics
type
Outcome* = distinct seq[AssetOutcome]
AssetOutcomeType* = enum
allocationType = 0
guaranteeType = 1
AssetOutcome* = object
assetHolder*: EthAddress
case kind*: AssetOutcomeType
of allocationType:
allocation*: Allocation
of guaranteeType:
guarantee*: Guarantee
Allocation* = distinct seq[AllocationItem]
2021-03-09 16:48:47 +01:00
AllocationItem* = tuple
destination: Destination
amount: UInt256
Guarantee* = object
targetChannelId*: Destination
destinations*: seq[Destination]
2021-03-17 12:22:00 +01:00
func init*(_: type Outcome,
2021-03-09 16:48:47 +01:00
asset: EthAddress,
allocation: openArray[AllocationItem]): Outcome =
let assetOutcome = AssetOutcome(
kind: allocationType,
assetHolder: asset,
allocation: Allocation(@allocation)
)
Outcome(@[assetOutcome])
2021-03-17 15:34:55 +01:00
proc `==`*(a, b: Allocation): bool {.borrow.}
2021-03-09 16:49:16 +01:00
2021-03-17 12:22:00 +01:00
func `==`*(a, b: AssetOutcome): bool =
2021-03-09 16:49:16 +01:00
if a.kind != b.kind:
return false
if a.assetHolder != b.assetHolder:
return false
case a.kind:
of allocationType:
a.allocation == b.allocation
of guaranteeType:
a.guarantee == b.guarantee
2021-03-17 15:34:55 +01:00
proc `==`*(a, b: Outcome): bool {.borrow.}
2021-03-09 16:49:16 +01:00
2021-03-17 12:22:00 +01:00
func encode*(encoder: var AbiEncoder, guarantee: Guarantee) =
encoder.write:
( (guarantee.targetChannelId, guarantee.destinations), )
2021-03-17 12:22:00 +01:00
func encode*(encoder: var AbiEncoder, allocation: Allocation) =
encoder.write: (seq[AllocationItem](allocation),)
2021-03-17 12:22:00 +01:00
func encode*(encoder: var AbiEncoder, assetOutcome: AssetOutcome) =
var content: seq[byte]
case assetOutcome.kind:
of allocationType:
content = AbiEncoder.encode:
( (assetOutcome.kind, ABiEncoder.encode(assetOutcome.allocation)), )
of guaranteeType:
content = AbiEncoder.encode:
( (assetOutcome.kind, AbiEncoder.encode(assetOutcome.guarantee)), )
encoder.write( (assetOutcome.assetHolder, content) )
2021-03-17 12:22:00 +01:00
func encode*(encoder: var AbiEncoder, outcome: Outcome) =
encoder.write: (seq[AssetOutcome](outcome),)
2021-03-17 12:22:00 +01:00
func hashOutcome*(outcome: Outcome): array[32, byte] =
keccak256.digest(AbiEncoder.encode(outcome)).data