|
| 1 | +// Copyright 2023 Blink Labs, LLC. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package ledger |
| 16 | + |
| 17 | +import ( |
| 18 | + "github.com/blinklabs-io/gouroboros/cbor" |
| 19 | +) |
| 20 | + |
| 21 | +// MultiAsset represents a collection of policies, assets, and quantities. It's used for |
| 22 | +// TX outputs (uint64) and TX asset minting (int64 to allow for negative values for burning) |
| 23 | +type MultiAsset[T int64 | uint64] struct { |
| 24 | + data map[Blake2b224]map[cbor.ByteString]T |
| 25 | +} |
| 26 | + |
| 27 | +func (m *MultiAsset[T]) UnmarshalCBOR(data []byte) error { |
| 28 | + _, err := cbor.Decode(data, &(m.data)) |
| 29 | + return err |
| 30 | +} |
| 31 | + |
| 32 | +func (m *MultiAsset[T]) MarshalCBOR() ([]byte, error) { |
| 33 | + return cbor.Encode(&(m.data)) |
| 34 | +} |
| 35 | + |
| 36 | +func (m *MultiAsset[T]) Policies() []Blake2b224 { |
| 37 | + var ret []Blake2b224 |
| 38 | + for policyId := range m.data { |
| 39 | + ret = append(ret, policyId) |
| 40 | + } |
| 41 | + return ret |
| 42 | +} |
| 43 | + |
| 44 | +func (m *MultiAsset[T]) Assets(policyId Blake2b224) [][]byte { |
| 45 | + assets, ok := m.data[policyId] |
| 46 | + if !ok { |
| 47 | + return nil |
| 48 | + } |
| 49 | + var ret [][]byte |
| 50 | + for assetName := range assets { |
| 51 | + ret = append(ret, assetName.Bytes()) |
| 52 | + } |
| 53 | + return ret |
| 54 | +} |
| 55 | + |
| 56 | +func (m *MultiAsset[T]) Asset(policyId Blake2b224, assetName []byte) T { |
| 57 | + policy, ok := m.data[policyId] |
| 58 | + if !ok { |
| 59 | + return 0 |
| 60 | + } |
| 61 | + return policy[cbor.ByteString(assetName)] |
| 62 | +} |
0 commit comments