basic-1.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const assert = require('assert');
  2. const anchor = require('@project-serum/anchor');
  3. describe('basic-1', () => {
  4. // Use a local provider.
  5. const provider = anchor.Provider.local()
  6. // Configure the client to use the local cluster.
  7. anchor.setProvider(provider);
  8. it('Creates and initializes an account in two different transactions', async () => {
  9. // The program owning the account to create.
  10. const program = anchor.workspace.Basic1;
  11. // The Account to create.
  12. const myAccount = new anchor.web3.Account();
  13. // Create account transaction.
  14. const tx = new anchor.web3.Transaction();
  15. tx.add(
  16. anchor.web3.SystemProgram.createAccount({
  17. fromPubkey: provider.wallet.publicKey,
  18. newAccountPubkey: myAccount.publicKey,
  19. space: 8,
  20. lamports: await provider.connection.getMinimumBalanceForRentExemption(8),
  21. programId: program.programId,
  22. }),
  23. );
  24. // Execute the transaction against the cluster.
  25. await provider.send(tx, [myAccount]);
  26. // Execute the RPC.
  27. // #region code-separated
  28. await program.rpc.initialize(new anchor.BN(1234), {
  29. accounts: {
  30. myAccount: myAccount.publicKey,
  31. },
  32. });
  33. // #endregion code-separated
  34. // Fetch the newly created account from the cluster.
  35. const account = await program.account.myAccount(myAccount.publicKey);
  36. // Check it's state was initialized.
  37. assert.ok(account.data.eq(new anchor.BN(1234)));
  38. });
  39. it('Creates and initializes an account in a single atomic transaction', async () => {
  40. // The program to execute.
  41. const program = anchor.workspace.Basic1;
  42. // #region code
  43. // The Account to create.
  44. const myAccount = new anchor.web3.Account();
  45. // Atomically create the new account and initialize it with the program.
  46. await program.rpc.initialize(new anchor.BN(1234), {
  47. accounts: {
  48. myAccount: myAccount.publicKey,
  49. },
  50. signers: [myAccount],
  51. instructions: [
  52. anchor.web3.SystemProgram.createAccount({
  53. fromPubkey: provider.wallet.publicKey,
  54. newAccountPubkey: myAccount.publicKey,
  55. space: 8,
  56. lamports: await provider.connection.getMinimumBalanceForRentExemption(8),
  57. programId: program.programId,
  58. }),
  59. ],
  60. });
  61. // Fetch the newly created account from the cluster.
  62. const account = await program.account.myAccount(myAccount.publicKey);
  63. // Check it's state was initialized.
  64. assert.ok(account.data.eq(new anchor.BN(1234)));
  65. // #endregion code
  66. });
  67. });