|
1 | 1 | package asset |
2 | 2 |
|
| 3 | +import ( |
| 4 | + "github.com/stellar/go/xdr" |
| 5 | + "strings" |
| 6 | +) |
| 7 | + |
3 | 8 | // NewNativeAsset creates an Asset representing the native token (XLM). |
4 | 9 | func NewNativeAsset() *Asset { |
5 | 10 | return &Asset{AssetType: &Asset_Native{Native: true}} |
6 | 11 | } |
7 | 12 |
|
8 | | -// NewIssuedAsset creates an Asset with an asset code and issuer. |
9 | | -func NewIssuedAsset(assetCode, issuer string) *Asset { |
| 13 | +func NewProtoAsset(asset xdr.Asset) *Asset { |
| 14 | + if asset.IsNative() { |
| 15 | + return NewNativeAsset() |
| 16 | + } |
10 | 17 | return &Asset{ |
11 | 18 | AssetType: &Asset_IssuedAsset{ |
12 | 19 | IssuedAsset: &IssuedAsset{ |
13 | | - AssetCode: assetCode, |
14 | | - Issuer: issuer, |
| 20 | + // Need to trim the extra null characters from showing in the code when saving to assetCode |
| 21 | + AssetCode: strings.TrimRight(asset.GetCode(), "\x00"), |
| 22 | + Issuer: asset.GetIssuer(), |
15 | 23 | }, |
16 | 24 | }, |
17 | 25 | } |
18 | 26 | } |
| 27 | + |
| 28 | +func (a *Asset) ToXdrAsset() xdr.Asset { |
| 29 | + if a == nil { |
| 30 | + panic("nil asset") |
| 31 | + } |
| 32 | + switch a := a.AssetType.(type) { |
| 33 | + case *Asset_Native: |
| 34 | + return xdr.MustNewNativeAsset() |
| 35 | + case *Asset_IssuedAsset: |
| 36 | + return xdr.MustNewCreditAsset(a.IssuedAsset.AssetCode, a.IssuedAsset.Issuer) |
| 37 | + } |
| 38 | + panic("unknown asset type") |
| 39 | +} |
| 40 | + |
| 41 | +func (a *Asset) Equals(other *Asset) bool { |
| 42 | + // If both assets are the same type (native or issued asset) |
| 43 | + if a.AssetType == nil || other.AssetType == nil { |
| 44 | + return false |
| 45 | + } |
| 46 | + |
| 47 | + switch a := a.AssetType.(type) { |
| 48 | + case *Asset_Native: |
| 49 | + if b, ok := other.AssetType.(*Asset_Native); ok { |
| 50 | + // Both assets are native; compare the native boolean value. |
| 51 | + // Ideally i could simply be returning true here, but it is more idiomatic to check for the flag equality |
| 52 | + return a.Native == b.Native |
| 53 | + } |
| 54 | + case *Asset_IssuedAsset: |
| 55 | + if b, ok := other.AssetType.(*Asset_IssuedAsset); ok { |
| 56 | + // Both assets are issued assets; compare their asset_code and issuer |
| 57 | + return a.IssuedAsset.AssetCode == b.IssuedAsset.AssetCode && |
| 58 | + a.IssuedAsset.Issuer == b.IssuedAsset.Issuer |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return false |
| 63 | +} |
0 commit comments