spl-associated-token-coder.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import * as anchor from "@project-serum/anchor";
  2. import { Native, Spl } from "@project-serum/anchor";
  3. import { Keypair, PublicKey } from "@solana/web3.js";
  4. import * as assert from "assert";
  5. import BN from "bn.js";
  6. describe("spl-associated-token-coder", () => {
  7. // Configure the client to use the local cluster.
  8. const provider = anchor.AnchorProvider.env();
  9. anchor.setProvider(provider);
  10. // Client.
  11. const program = Spl.associatedToken();
  12. const systemProgram = Native.system();
  13. const tokenProgram = Spl.token();
  14. it("Creates an account", async () => {
  15. // arrange
  16. const mintKeypair = Keypair.generate();
  17. const mintDecimals = 6;
  18. const mintSize = tokenProgram.coder.accounts.size(
  19. tokenProgram.idl.accounts[0]
  20. );
  21. const mintRentExemption =
  22. await provider.connection.getMinimumBalanceForRentExemption(mintSize);
  23. const [associatedToken] = await PublicKey.findProgramAddress(
  24. [
  25. provider.publicKey.toBuffer(),
  26. tokenProgram.programId.toBuffer(),
  27. mintKeypair.publicKey.toBuffer(),
  28. ],
  29. program.programId
  30. );
  31. // act
  32. await program.methods
  33. .create()
  34. .accounts({
  35. authority: provider.wallet.publicKey,
  36. mint: mintKeypair.publicKey,
  37. owner: provider.wallet.publicKey,
  38. associatedAccount: associatedToken,
  39. })
  40. .preInstructions(
  41. await Promise.all([
  42. systemProgram.methods
  43. .createAccount(
  44. new BN(mintRentExemption),
  45. new BN(mintSize),
  46. tokenProgram.programId
  47. )
  48. .accounts({
  49. from: provider.wallet.publicKey,
  50. to: mintKeypair.publicKey,
  51. })
  52. .instruction(),
  53. tokenProgram.methods
  54. .initializeMint(mintDecimals, provider.wallet.publicKey, null)
  55. .accounts({
  56. mint: mintKeypair.publicKey,
  57. })
  58. .instruction(),
  59. ])
  60. )
  61. .signers([mintKeypair])
  62. .rpc();
  63. // assert
  64. const tokenAccount = await tokenProgram.account.token.fetch(
  65. associatedToken
  66. );
  67. assert.ok(tokenAccount.mint.equals(mintKeypair.publicKey));
  68. });
  69. });