Răsfoiți Sursa

Identity com bugfix/robust fetch nullable (#2301)

* ts: Fixed `.fetchNullable()` to be robust towards accounts only holding a balance

* update changelog to new PR id

* prettier

Co-authored-by: Martin Riedel <web@riedel-it.de>
Co-authored-by: henrye <henry@notanemail>
Henry-E 2 ani în urmă
părinte
comite
09b829d1a3

+ 1 - 0
CHANGELOG.md

@@ -44,6 +44,7 @@ The minor version will be incremented upon a breaking change and the patch versi
 - event: Fix multiple event listeners with the same name ([#2165](https://github.com/coral-xyz/anchor/pull/2165)).
 - lang: Prevent the payer account from being initialized as a program account ([#2284](https://github.com/coral-xyz/anchor/pull/2284)).
 - ts: Fixing breaking change where null or undefined wallet throws an error ([#2303](https://github.com/coral-xyz/anchor/pull/2303)).
+- ts: Fixed `.fetchNullable()` to be robust towards accounts only holding a balance ([#2301](https://github.com/coral-xyz/anchor/pull/2301)).
 
 ### Breaking
 

+ 14 - 0
tests/misc/tests/misc/misc.ts

@@ -787,6 +787,20 @@ describe("misc", () => {
     assert.strictEqual(account2.idata.toNumber(), 3);
   });
 
+  it("Can use fetchNullable() on accounts with only a balance", async () => {
+    const account = anchor.web3.Keypair.generate();
+
+    // Airdrop 1 SOL to the account.
+    const signature = await program.provider.connection.requestAirdrop(
+      account.publicKey,
+      anchor.web3.LAMPORTS_PER_SOL
+    );
+    await program.provider.connection.confirmTransaction(signature);
+
+    const data = await program.account.data.fetchNullable(account.publicKey);
+    assert.isNull(data);
+  });
+
   describe("associated_token constraints", () => {
     let associatedToken = null;
     // apparently cannot await here so doing it in the 'it' statements

+ 7 - 4
ts/packages/anchor/src/program/namespace/account.ts

@@ -154,9 +154,10 @@ export class AccountClient<
     );
     const { value, context } = accountInfo;
     return {
-      data: value
-        ? this._coder.accounts.decode<T>(this._idlAccount.name, value.data)
-        : null,
+      data:
+        value && value.data.length !== 0
+          ? this._coder.accounts.decode<T>(this._idlAccount.name, value.data)
+          : null,
       context,
     };
   }
@@ -169,7 +170,9 @@ export class AccountClient<
   async fetch(address: Address, commitment?: Commitment): Promise<T> {
     const { data } = await this.fetchNullableAndContext(address, commitment);
     if (data === null) {
-      throw new Error(`Account does not exist ${address.toString()}`);
+      throw new Error(
+        `Account does not exist or has no data ${address.toString()}`
+      );
     }
     return data;
   }