Skip to content

Commit 3391d5d

Browse files
committed
feat: Fetch symbol if missing (#596)
1 parent 5ecb8d3 commit 3391d5d

File tree

1 file changed

+65
-2
lines changed

1 file changed

+65
-2
lines changed

packages/ethereum/MobileAdapter.ts

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,62 @@ export class MobileAdapter {
104104
const { options, type } = args.params as unknown as IWatchAsset;
105105
const { address, symbol, decimals } = options;
106106

107+
let fetchedSymbol;
108+
let fetchedDecimals;
109+
110+
if (!symbol) {
111+
try {
112+
// call for symbol() = 0x95d89b41
113+
const result = await this.contractCall(address, '0x95d89b41');
114+
const hexString = result.slice(2);
115+
116+
// The offset is the position where the dynamic data starts
117+
const offset = parseInt(hexString.slice(0, 64), 16);
118+
119+
// The length of the string is at the offset position
120+
const length = parseInt(
121+
hexString.slice(offset * 2, offset * 2 + 64),
122+
16,
123+
);
124+
125+
// The actual string data starts right after the length field
126+
const stringDataStart = offset * 2 + 64;
127+
const stringDataHex = hexString.slice(
128+
stringDataStart,
129+
stringDataStart + length * 2,
130+
);
131+
132+
fetchedSymbol = '';
133+
134+
for (let i = 0; i < stringDataHex.length; i += 2) {
135+
const hexChar = stringDataHex.slice(i, i + 2);
136+
const char = String.fromCharCode(parseInt(hexChar, 16));
137+
138+
if (char === '\x00') break;
139+
fetchedSymbol += char;
140+
}
141+
} catch (e) {
142+
console.error(e);
143+
}
144+
}
145+
146+
if (!decimals) {
147+
try {
148+
// call for decimals() = 0x313ce567
149+
const result = await this.contractCall(address, '0x313ce567');
150+
fetchedDecimals = parseInt(result, 16);
151+
} catch (e) {
152+
console.error(e);
153+
}
154+
}
155+
107156
return this.provider.internalRequest({
108157
method: 'watchAsset',
109158
params: {
110159
type,
111160
contract: address,
112-
symbol,
113-
decimals: decimals || 0,
161+
symbol: symbol || fetchedSymbol,
162+
decimals: decimals || fetchedDecimals,
114163
},
115164
});
116165
}
@@ -247,4 +296,18 @@ export class MobileAdapter {
247296
},
248297
});
249298
}
299+
300+
contractCall(address: string, method: string) {
301+
return this.provider.getRPC().call({
302+
method: 'eth_call',
303+
jsonrpc: '2.0',
304+
params: [
305+
{
306+
to: address,
307+
data: method,
308+
},
309+
'latest',
310+
],
311+
});
312+
}
250313
}

0 commit comments

Comments
 (0)