3

I found pretty interesting documentation on spl.solana.com however I believe it's not accurate on one side!

The section below taken from the site shows a way we can send spl tokens, via JS by funding the account of the user IF they don't have an associated account.

Example: Transferring tokens to another user, with sender-funding If the receiver does not yet have an associated token account, the sender may choose to fund the receiver's account. The receiver obtains their wallet address by running Solana address and providing it to the sender. The sender then runs to fund the receiver's associated token account, at the sender's expense, and then transfers 50 tokens into it:

After creating an SPL token successfully and minting it, the code for transfer recommended on docs looks something like this

const signature = await transfer(
connection,
toWallet,
fromTokenAccount.address,
toTokenAccount.address,
fromWallet.publicKey,
50,
[fromWallet, toWallet]);

Pretty straightforward, except that it doesn't make sense since we don't have toWallet. In the previous code sample provided, their toWallet is generated by the following code const toWallet = Keypair.generate();

Considering that in this case, "the receiver obtains their wallet address by running Solana address and provides it to the sender", what is your approach to sending the token transfer when toWallet parameter cannot exist?

My attempt was to send it over using the public key but it doesn't seem to go through

signature = await transfer(
    connection,
    "8GT5wqNYX7SqLHNvTvcsFAT9FHZEWSkXynThioDXqHab",
    tokenAccount.address,
    toTokenAccount.address,
    payer.publicKey,
    50,
    [payer, "8GT5wqNYX7SqLHNvTvcsFAT9FHZEWSkXynThioDXqHab"]
);

1 Answer 1

3

You can create the token account first, which you can do in JS like this:

const toTokenAccount = await getOrCreateAssociatedTokenAccount(
  connection,
  payer, // this is the funder (a signer)
  mint,
  toWallet.publicKey // this is the owner of the created account (the receiver)
)

This allows you to pay to create a token account for the mint for any public key

You can see this in the context of a different example in the docs: https://spl.solana.com/token#example-transferring-tokens-to-another-user

It's also documented here in the JS docs: https://solana-labs.github.io/solana-program-library/token/js/modules.html#getOrCreateAssociatedTokenAccount

I agree that the doc you mentioned is unclear because you don't have toTokenAccount, by definition. I think we just need to add a getOrCreateAssociatedTokenAccount code block to create it, but I'll make a note to take a closer look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.