Solidity <> JS primitive types #93
Answered
by
tmm
frolic
asked this question in
Idea / Feature Request
|
I don't have a particular proposal, but would like to start a discussion around how best to translate Solidity types into JS and back. Some questions I have:
|
Answered by
tmm
Mar 1, 2023
Replies: 2 comments 4 replies
|
Do you mean at runtime, type-level, or both? |
4 replies
Answer selected by
frolic
|
The Solidity ↔ JS type mapping in viem is one of its strongest features — it infers TypeScript types from ABI definitions at compile time. Here's a quick reference: Solidity → TypeScript mapping:
Practical example with full type inference: import { createPublicClient, http, parseAbi } from 'viem';
import { mainnet } from 'viem/chains';
const abi = parseAbi([
'function balanceOf(address owner) view returns (uint256)',
'function transfer(address to, uint256 amount) returns (bool)',
'event Transfer(address indexed from, address indexed to, uint256 value)',
]);
const client = createPublicClient({ chain: mainnet, transport: http() });
// TypeScript knows: returns bigint (from uint256)
const balance: bigint = await client.readContract({
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
abi,
functionName: 'balanceOf',
args: ['0x...'], // TypeScript enforces: must be `0x${string}`
});
// TypeScript knows: amount must be bigint, to must be `0x${string}`
await client.writeContract({
address: '0x...',
abi,
functionName: 'transfer',
args: ['0x...', 1000000n], // n suffix = bigint literal
});The |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you mean at runtime, type-level, or both?