bmresearch / Solnet

Solana's .NET SDK and integration library.
https://blockmountain.io/Solnet
MIT License
324 stars 130 forks source link

getOrCreateAssociatedTokenAccount #429

Closed h0lym4n closed 1 year ago

h0lym4n commented 1 year ago

I want to use function like getOrCreateAssociatedTokenAccount with solnet.

js const tokenAccount = await getOrCreateAssociatedTokenAccount( connection, payer, mint, payer.publicKey )

I want to create a token account in the recipient wallet and send tokens to it, but I failed to do so. Do you have a sample code script?

BifrostTitan commented 1 year ago

Join the solnet discord if you have any questions. Try not to open an issue when needing assistance unless its error related

This is for creating a token account and sending SPL tokens. `

            Wallet wallet = new Wallet(mnemonic: new Mnemonic("your key goes here"), passphrase: "your pw goes here");
            Account walletOwner = wallet.GetAccount(0);
            var rpcClient = Solnet.Rpc.ClientFactory.GetClient("your rpc provider uri goes here");

            PublicKey mint = new PublicKey("token mint address goes here");
            PublicKey recipient = new PublicKey("recipient address goes here");

            RequestResult<ResponseValue<BlockHash>> blockHash = await rpcClient.GetRecentBlockHashAsync();

            byte[] transferTx = new TransactionBuilder().
            SetRecentBlockHash(blockHash.Result.Value.Blockhash).
            SetFeePayer(walletOwner).
            AddInstruction(AssociatedTokenAccountProgram.CreateAssociatedTokenAccount(walletOwner, recipient, mint)).
            AddInstruction(TokenProgram.Transfer(AssociatedTokenAccountProgram.DeriveAssociatedTokenAccount(walletOwner, mint), AssociatedTokenAccountProgram.DeriveAssociatedTokenAccount(recipient, mint), SolHelper.ConvertToLamports(amount), walletOwner)).
            Build(new List<Account> { walletOwner });

            var tx = await rpcClient.SendTransactionAsync(transferTx); 

`

This is to transfer sol

AddInstruction(TokenProgram.Transfer(walletOwner, recipient, SolHelper.ConvertToLamports(amount), walletOwner)).