Skip to content

Commit 523cd1e

Browse files
authored
shortenAddress util (#2995)
1 parent a58d116 commit 523cd1e

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

.changeset/sixty-forks-repeat.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"thirdweb": minor
3+
---
4+
5+
Adds shortenAddress util

packages/thirdweb/src/exports/utils.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ export {
124124
checksumAddress,
125125
getAddress,
126126
isAddress,
127+
shortenAddress,
127128
type Address,
128129
type AddressInput,
129130
} from "../utils/address.js";

packages/thirdweb/src/utils/address.test.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import { describe, expect, test } from "vitest";
22

3-
import { checksumAddress, getAddress, isAddress } from "./address.js";
3+
import {
4+
checksumAddress,
5+
getAddress,
6+
isAddress,
7+
shortenAddress,
8+
} from "./address.js";
49

510
describe("getAddress", () => {
611
test("checksums address", () => {
@@ -81,3 +86,11 @@ describe("checksumAddress", () => {
8186
).toMatchInlineSnapshot('"0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65"');
8287
});
8388
});
89+
90+
describe("shortenAddress", () => {
91+
test("shortens address", () => {
92+
expect(
93+
shortenAddress("0xa0cf798816d4b9b9866b5330eea46a18382f251e"),
94+
).toMatchInlineSnapshot('"0xA0...251e"');
95+
});
96+
});

packages/thirdweb/src/utils/address.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,22 @@ export function getAddress(address: string): Address {
9595
}
9696
return checksumAddress(address);
9797
}
98+
99+
/**
100+
* Checksums and formats an address if valid. Note this function does not check if the provided address is an ENS.
101+
* @param address - The address to shorten.
102+
* @param length - The number of characters to keep from the start and end of the address.
103+
* @returns The shortened address.
104+
* @example
105+
* ```ts
106+
* import { shortenAddress } from 'thirdweb/utils';
107+
*
108+
* shortenAddress('0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed');
109+
* //=> '0x5aAe...Ef1BeAed'
110+
* ```
111+
* @utils
112+
*/
113+
export function shortenAddress(address: Address, length = 4) {
114+
const _address = getAddress(address);
115+
return `${_address.slice(0, length)}...${_address.slice(-length)}`;
116+
}

0 commit comments

Comments
 (0)