github.com/gagliardetto/solana-go@v1.11.0/rpc/getTokenAccountsByOwner.go (about)

     1  // Copyright 2021 github.com/gagliardetto
     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 rpc
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  
    21  	"github.com/gagliardetto/solana-go"
    22  )
    23  
    24  // GetTokenAccountsByOwner returns all SPL Token accounts by token owner.
    25  func (cl *Client) GetTokenAccountsByOwner(
    26  	ctx context.Context,
    27  	owner solana.PublicKey,
    28  	conf *GetTokenAccountsConfig,
    29  	opts *GetTokenAccountsOpts,
    30  ) (out *GetTokenAccountsResult, err error) {
    31  	params := []interface{}{owner}
    32  	if conf == nil {
    33  		return nil, errors.New("conf is nil")
    34  	}
    35  	if conf.Mint != nil && conf.ProgramId != nil {
    36  		return nil, errors.New("conf.Mint and conf.ProgramId are both set; must be just one of them")
    37  	}
    38  
    39  	{
    40  		confObj := M{}
    41  		if conf.Mint != nil {
    42  			confObj["mint"] = conf.Mint
    43  		}
    44  		if conf.ProgramId != nil {
    45  			confObj["programId"] = conf.ProgramId
    46  		}
    47  		if len(confObj) > 0 {
    48  			params = append(params, confObj)
    49  		}
    50  	}
    51  	defaultEncoding := solana.EncodingBase64
    52  	{
    53  		optsObj := M{}
    54  		if opts != nil {
    55  			if opts.Commitment != "" {
    56  				optsObj["commitment"] = opts.Commitment
    57  			}
    58  			if opts.Encoding != "" {
    59  				optsObj["encoding"] = opts.Encoding
    60  			} else {
    61  				optsObj["encoding"] = defaultEncoding
    62  			}
    63  			if opts.DataSlice != nil {
    64  				optsObj["dataSlice"] = M{
    65  					"offset": opts.DataSlice.Offset,
    66  					"length": opts.DataSlice.Length,
    67  				}
    68  				if opts.Encoding == solana.EncodingJSONParsed {
    69  					return nil, errors.New("cannot use dataSlice with EncodingJSONParsed")
    70  				}
    71  			}
    72  			if len(optsObj) > 0 {
    73  				params = append(params, optsObj)
    74  			}
    75  		} else {
    76  			params = append(params, M{"encoding": defaultEncoding})
    77  		}
    78  	}
    79  
    80  	err = cl.rpcClient.CallForInto(ctx, &out, "getTokenAccountsByOwner", params)
    81  	return
    82  }