Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: reject owner changed ATA #25

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/common-sdk/src/web3/ata-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ export async function resolveOrCreateATAs(
const ataAddress = nonNativeAddresses[index]!;
let resolvedInstruction;
if (tokenAccount) {
// ATA whose owner has been changed is abnormal entity.
// To prevent to send swap/withdraw/collect output to the ATA, an error should be thrown.
if (!tokenAccount.owner.equals(ownerAddress)) {
throw new Error(`ATA with change of ownership detected: ${ataAddress.toBase58()}`);
}

resolvedInstruction = { address: ataAddress, ...EMPTY_INSTRUCTION };
} else {
const createAtaInstruction = createAssociatedTokenAccountInstruction(
Expand Down
47 changes: 47 additions & 0 deletions packages/common-sdk/tests/ata-util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,4 +242,51 @@ describe("ata-util", () => {
expect(postAccountData[1]).not.toBeNull();
expect(postAccountData[2]).not.toBeNull();
});

it("resolveOrCreateATA, owner changed ATA detected", async () => {
const anotherWallet = Keypair.generate();
const mint = await createNewMint();

const ata = await mint.createAssociatedTokenAccount(wallet.publicKey);

// should be ok
const preOwnerChanged = await resolveOrCreateATA(
connection,
wallet.publicKey,
mint.publicKey,
() => connection.getMinimumBalanceForRentExemption(AccountLayout.span),
);
expect(preOwnerChanged.address.equals(ata)).toBeTruthy();

// owner change
const builder = new TransactionBuilder(connection, wallet);
builder.addInstruction({
instructions: [
Token.createSetAuthorityInstruction(
TOKEN_PROGRAM_ID,
ata,
anotherWallet.publicKey,
"AccountOwner",
wallet.publicKey,
[]
)
],
cleanupInstructions: [],
signers: [],
});
await builder.buildAndExecute();

// verify that owner have been changed
const changed = await mint.getAccountInfo(ata);
expect(changed.owner.equals(anotherWallet.publicKey)).toBeTruthy();

// should be failed
const postOwnerChangedPromise = resolveOrCreateATA(
connection,
wallet.publicKey,
mint.publicKey,
() => connection.getMinimumBalanceForRentExemption(AccountLayout.span),
);
await expect(postOwnerChangedPromise).rejects.toThrow(/ATA with change of ownership detected/);
});
});