Skip to content

Commit

Permalink
feat: user asset balance (#176)
Browse files Browse the repository at this point in the history
Co-authored-by: Crossle Song <[email protected]>
  • Loading branch information
zzwzzhao and crossle committed Aug 7, 2024
1 parent c2b8b48 commit 0af3196
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,25 @@ func AssetBalanceWithSafeUser(ctx context.Context, kernelAssetId string, su *Saf
return total, nil
}


func UserAssetBalance(ctx context.Context, userID, assetID, accessToken string) (common.Integer, error) {
if id, _ := uuid.FromString(assetID); assetID == id.String() {
assetID = crypto.Sha256Hash([]byte(assetID)).String()
}

membersHash := HashMembers([]string{userID})
outputs, err := ListUnspentOutputsByToken(ctx, membersHash, 1, assetID, accessToken)
if err != nil {
return common.Zero, err
}
var total common.Integer
for _, o := range outputs {
amt := common.NewIntegerFromString(o.Amount)
total = total.Add(amt)
}
return total, nil
}

func ReadAssetFee(ctx context.Context, assetId, destination string, su *SafeUser) ([]*AssetFee, error) {
params := url.Values{}
params.Set("destination", destination)
Expand Down
35 changes: 35 additions & 0 deletions output.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,41 @@ func ListOutputs(ctx context.Context, membersHash string, threshold byte, assetI
return resp.Data, nil
}

func ListUnspentOutputsByToken(ctx context.Context, membersHash string, threshold byte, kernelAssetId string, accessToken string) ([]*Output, error) {
return ListOutputsByToken(ctx, membersHash, threshold, kernelAssetId, "unspent", 0, 500, accessToken)
}

func ListOutputsByToken(ctx context.Context, membersHash string, threshold byte, assetId, state string, offset uint64, limit int, accessToken string) ([]*Output, error) {
v := url.Values{}
v.Set("members", membersHash)
v.Set("threshold", fmt.Sprint(threshold))
v.Set("limit", strconv.Itoa(limit))
if offset > 0 {
v.Set("offset", fmt.Sprint(offset))
}
if assetId != "" {
v.Set("asset", assetId)
}
if state != "" {
v.Set("state", state)
}
method, path := "GET", fmt.Sprintf("/safe/outputs?"+v.Encode())
body, err := Request(ctx, method, path, []byte{}, accessToken)

var resp struct {
Data []*Output `json:"data"`
Error Error `json:"error"`
}
err = json.Unmarshal(body, &resp)
if err != nil {
return nil, BadDataError(ctx)
}
if resp.Error.Code > 0 {
return nil, resp.Error
}
return resp.Data, nil
}

func GetOutput(ctx context.Context, id string, u *SafeUser) (*Output, error) {
method, path := "GET", fmt.Sprintf("/safe/outputs/%s", id)
token, err := SignAuthenticationToken(method, path, "", u)
Expand Down

0 comments on commit 0af3196

Please sign in to comment.