Skip to content

[SDK] Feature: Track insufficient funds error across SDK #7256

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

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
109 changes: 109 additions & 0 deletions packages/thirdweb/src/analytics/track/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import { getErrorDetails, isInsufficientFundsError } from "./helpers.js";

describe("isInsufficientFundsError", () => {
it("should detect basic insufficient funds error message", () => {
const error = new Error("insufficient funds");
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect insufficient funds for gas error", () => {
const error = new Error("Insufficient funds for gas * price + value");
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect insufficient funds for intrinsic transaction cost", () => {
const error = new Error(
"insufficient funds for intrinsic transaction cost",
);
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect insufficient balance error", () => {
const error = new Error("insufficient balance");
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect insufficient native funds error", () => {
const error = new Error("Insufficient Native Funds");
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect INSUFFICIENT_FUNDS error code", () => {
const error = { code: "INSUFFICIENT_FUNDS", message: "Transaction failed" };
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect reason field", () => {
const error = {
reason: "insufficient funds",
message: "Transaction failed",
};
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should detect error in nested data.message", () => {
const error = { data: { message: "insufficient funds for gas" } };
expect(isInsufficientFundsError(error)).toBe(true);
});

it("should handle string errors", () => {
expect(isInsufficientFundsError("insufficient funds")).toBe(true);
});

it("should return false for non-insufficient funds errors", () => {
const error = new Error("User rejected transaction");
expect(isInsufficientFundsError(error)).toBe(false);
});

it("should return false for null/undefined", () => {
expect(isInsufficientFundsError(null)).toBe(false);
expect(isInsufficientFundsError(undefined)).toBe(false);
});

it("should be case insensitive", () => {
const error = new Error("INSUFFICIENT FUNDS FOR GAS");
expect(isInsufficientFundsError(error)).toBe(true);
});
});

describe("getErrorDetails", () => {
it("should extract message and code from Error object", () => {
const error = new Error("Test error message");
const details = getErrorDetails(error);
expect(details.message).toBe("Test error message");
expect(details.code).toBeUndefined();
});

it("should extract message and code from error object", () => {
const error = { message: "Test message", code: "TEST_CODE" };
const details = getErrorDetails(error);
expect(details.message).toBe("Test message");
expect(details.code).toBe("TEST_CODE");
});

it("should extract message from nested data", () => {
const error = { data: { message: "Nested error message" } };
const details = getErrorDetails(error);
expect(details.message).toBe("Nested error message");
});

it("should handle string errors", () => {
const details = getErrorDetails("String error");
expect(details.message).toBe("String error");
expect(details.code).toBeUndefined();
});

it("should handle null/undefined", () => {
const details = getErrorDetails(null);
expect(details.message).toBe("Unknown error");
expect(details.code).toBeUndefined();
});

it("should extract reason as code", () => {
const error = { message: "Test message", reason: "test_reason" };
const details = getErrorDetails(error);
expect(details.message).toBe("Test message");
expect(details.code).toBe("test_reason");
});
});
49 changes: 49 additions & 0 deletions packages/thirdweb/src/analytics/track/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @internal
*/
export function isInsufficientFundsError(error: Error | unknown): boolean {
if (!error) return false;

const errorMessage =
typeof error === "string"
? error
: (error as Error)?.message ||
(error as { data?: { message?: string } })?.data?.message ||
"";

Check warning on line 12 in packages/thirdweb/src/analytics/track/helpers.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/analytics/track/helpers.ts#L12

Added line #L12 was not covered by tests

const message = errorMessage.toLowerCase();

// Common patterns for insufficient funds errors
return (
message.includes("insufficient funds") ||
message.includes("insufficient balance") ||
(message.includes("insufficient") &&
(message.includes("native") || message.includes("gas"))) ||
// Common error codes from various wallets/providers
(error as { code?: string | number })?.code === "INSUFFICIENT_FUNDS" ||
(error as { reason?: string })?.reason === "insufficient funds"
);
}

/**
* @internal
*/
export function getErrorDetails(error: Error | unknown): {
message: string;
code?: string | number;
} {
if (!error) return { message: "Unknown error" };

const message =
typeof error === "string"
? error
: (error as Error)?.message ||
(error as { data?: { message?: string } })?.data?.message ||
String(error);

Check warning on line 42 in packages/thirdweb/src/analytics/track/helpers.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/analytics/track/helpers.ts#L42

Added line #L42 was not covered by tests

const code =
(error as { code?: string | number })?.code ||
(error as { reason?: string })?.reason;

return { message, code };
}
111 changes: 110 additions & 1 deletion packages/thirdweb/src/analytics/track/transaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import type { ThirdwebClient } from "../../client/client.js";
import { trackTransaction } from "./transaction.js";
import {
trackInsufficientFundsError,
trackTransaction,
} from "./transaction.js";

const server = setupServer(
http.post("https://c.thirdweb.com/event", () => {
Expand Down Expand Up @@ -127,4 +130,110 @@ describe("transaction tracking", () => {
"test-partner-id",
);
});

it("should track insufficient funds error with correct data", async () => {
const mockClient: ThirdwebClient = {
clientId: "test-client-id",
secretKey: undefined,
};

let requestBody: unknown;
server.use(
http.post("https://c.thirdweb.com/event", async (handler) => {
requestBody = await handler.request.json();
return HttpResponse.json({});
}),
);

const mockError = new Error("Insufficient funds for gas * price + value");

await trackInsufficientFundsError({
client: mockClient,
error: mockError,
walletAddress: "0x1234567890123456789012345678901234567890",
chainId: 1,
contractAddress: "0xcontract",
transactionValue: 1000000000000000000n,
});

expect(requestBody).toEqual({
source: "sdk",
action: "transaction:insufficient_funds",
clientId: "test-client-id",
chainId: 1,
walletAddress: "0x1234567890123456789012345678901234567890",
contractAddress: "0xcontract",
transactionValue: "1000000000000000000",
requiredAmount: undefined,
userBalance: undefined,
errorMessage: "Insufficient funds for gas * price + value",
errorCode: undefined,
});
});

it("should not throw an error if insufficient funds tracking request fails", async () => {
const mockClient: ThirdwebClient = {
clientId: "test-client-id",
secretKey: undefined,
};

server.use(
http.post("https://c.thirdweb.com/event", () => {
return HttpResponse.error();
}),
);

const mockError = new Error("insufficient funds");

expect(() =>
trackInsufficientFundsError({
client: mockClient,
error: mockError,
walletAddress: "0x1234567890123456789012345678901234567890",
chainId: 137,
}),
).not.toThrowError();

// Wait for the asynchronous POST request to complete
await new Promise((resolve) => setTimeout(resolve, 100));
});

it("should track insufficient funds error during transaction preparation", async () => {
const mockClient: ThirdwebClient = {
clientId: "test-client-id",
secretKey: undefined,
};

let requestBody: unknown;
server.use(
http.post("https://c.thirdweb.com/event", async (handler) => {
requestBody = await handler.request.json();
return HttpResponse.json({});
}),
);

const mockError = new Error("insufficient funds for gas");

await trackInsufficientFundsError({
client: mockClient,
error: mockError,
walletAddress: "0xabcdef1234567890abcdef1234567890abcdef12",
chainId: 42,
contractAddress: "0x0987654321098765432109876543210987654321",
});

expect(requestBody).toEqual({
source: "sdk",
action: "transaction:insufficient_funds",
clientId: "test-client-id",
chainId: 42,
walletAddress: "0xabcdef1234567890abcdef1234567890abcdef12",
contractAddress: "0x0987654321098765432109876543210987654321",
transactionValue: undefined,
requiredAmount: undefined,
userBalance: undefined,
errorMessage: "insufficient funds for gas",
errorCode: undefined,
});
});
});
37 changes: 37 additions & 0 deletions packages/thirdweb/src/analytics/track/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ThirdwebClient } from "../../client/client.js";
import { stringify } from "../../utils/json.js";
import type { Ecosystem } from "../../wallets/in-app/core/wallet/types.js";
import type { WalletId } from "../../wallets/wallet-types.js";
import { getErrorDetails } from "./helpers.js";
import { track } from "./index.js";

type TransactionEvent = {
Expand Down Expand Up @@ -55,3 +56,39 @@ function trackTransactionEvent(
},
});
}

/**
* @internal
*/
export async function trackInsufficientFundsError(args: {
client: ThirdwebClient;
ecosystem?: Ecosystem;
error: Error | unknown;
walletAddress?: string;
chainId?: number;
contractAddress?: string;
functionName?: string;
transactionValue?: bigint;
requiredAmount?: bigint;
userBalance?: bigint;
}) {
const errorDetails = getErrorDetails(args.error);

return track({
client: args.client,
ecosystem: args.ecosystem,
data: {
action: "transaction:insufficient_funds",
clientId: args.client.clientId,
chainId: args.chainId,
walletAddress: args.walletAddress,
contractAddress: args.contractAddress,
functionName: args.functionName,
transactionValue: args.transactionValue?.toString(),
requiredAmount: args.requiredAmount?.toString(),
userBalance: args.userBalance?.toString(),
errorMessage: errorDetails.message,
errorCode: errorDetails.code ? stringify(errorDetails.code) : undefined,
},
});
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { type UseMutationResult, useMutation } from "@tanstack/react-query";
import { isInsufficientFundsError } from "../../../../analytics/track/helpers.js";
import { trackPayEvent } from "../../../../analytics/track/pay.js";
import { trackInsufficientFundsError } from "../../../../analytics/track/transaction.js";
import * as Bridge from "../../../../bridge/index.js";
import type { Chain } from "../../../../chains/types.js";
import type { BuyWithCryptoStatus } from "../../../../pay/buyWithCrypto/getStatus.js";
Expand Down Expand Up @@ -174,6 +176,18 @@

resolve(res);
} catch (e) {
// Track insufficient funds errors specifically
if (isInsufficientFundsError(e)) {
trackInsufficientFundsError({
client: tx.client,
error: e,
walletAddress: account.address,
chainId: tx.chain.id,
contractAddress: await resolvePromisedValue(tx.to ?? undefined),
transactionValue: await resolvePromisedValue(tx.value),
});
}

Check warning on line 189 in packages/thirdweb/src/react/core/hooks/transaction/useSendTransaction.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/transaction/useSendTransaction.ts#L180-L189

Added lines #L180 - L189 were not covered by tests

reject(e);
}
};
Expand Down
2 changes: 2 additions & 0 deletions packages/thirdweb/src/transaction/actions/estimate-gas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
throw await extractError({
error,
contract: options.transaction.__contract,
fromAddress,

Check warning on line 97 in packages/thirdweb/src/transaction/actions/estimate-gas.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/transaction/actions/estimate-gas.ts#L97

Added line #L97 was not covered by tests
});
}
}
Expand Down Expand Up @@ -150,6 +151,7 @@
throw await extractError({
error,
contract: options.transaction.__contract,
fromAddress,
});
}
})();
Expand Down
1 change: 1 addition & 0 deletions packages/thirdweb/src/transaction/actions/simulate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
throw await extractError({
error,
contract: options.transaction.__contract,
fromAddress: from,

Check warning on line 92 in packages/thirdweb/src/transaction/actions/simulate.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/transaction/actions/simulate.ts#L92

Added line #L92 was not covered by tests
});
}
}
Loading
Loading