Skip to content

Commit 88c9939

Browse files
committed
Fetch native currency from chain API when required
1 parent 2779afc commit 88c9939

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

.changeset/forty-donuts-happen.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"thirdweb": patch
3+
---
4+
5+
fetch native currency from chain API if required

packages/thirdweb/src/extensions/erc20/read/getCurrencyMetadata.ts

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
1+
import z from "zod";
12
import { isNativeTokenAddress } from "../../../constants/addresses.js";
23
import type { BaseTransactionOptions } from "../../../transaction/types.js";
34
import { name } from "../../common/read/name.js";
45
import { symbol } from "../../common/read/symbol.js";
56
import { decimals } from "../__generated__/IERC20/read/decimals.js";
67

8+
const NATIVE_CURRENCY_SCHEMA = z
9+
.object({
10+
name: z.string().default("Ether"),
11+
symbol: z.string().default("ETH"),
12+
decimals: z.number().default(18),
13+
})
14+
.default({
15+
name: "Ether",
16+
symbol: "ETH",
17+
decimals: 18,
18+
});
19+
720
/**
821
* @extension ERC20
922
*/
@@ -30,13 +43,19 @@ export async function getCurrencyMetadata(
3043
): Promise<GetCurrencyMetadataResult> {
3144
// if the contract is the native token, return the native currency metadata
3245
if (isNativeTokenAddress(options.contract.address)) {
33-
return {
34-
decimals: 18,
35-
name: "Ether",
36-
symbol: "ETH",
37-
// overwrite with native currency of the chain if available
38-
...options.contract.chain.nativeCurrency,
39-
};
46+
// if the chain definition does not have a native currency, attempt to fetch it from the API
47+
if (!options.contract.chain.nativeCurrency) {
48+
try {
49+
const { getChainMetadata } = await import("../../../chains/utils.js");
50+
const chain = await getChainMetadata(options.contract.chain);
51+
// return the native currency of the chain
52+
return NATIVE_CURRENCY_SCHEMA.parse(chain.nativeCurrency);
53+
} catch {
54+
// no-op, fall through to the default values below
55+
}
56+
}
57+
58+
return NATIVE_CURRENCY_SCHEMA.parse(options.contract.chain.nativeCurrency);
4059
}
4160

4261
try {

0 commit comments

Comments
 (0)