@ethersproject/abi#Interface TypeScript Examples
The following examples show how to use
@ethersproject/abi#Interface.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: hooks.ts From interface-v2 with GNU General Public License v3.0 | 6 votes |
function toCallState(
callResult: CallResult | undefined,
contractInterface: Interface | undefined,
fragment: FunctionFragment | undefined,
latestBlockNumber: number | undefined,
): CallState {
if (!callResult) return INVALID_CALL_STATE;
const { valid, data, blockNumber } = callResult;
if (!valid) return INVALID_CALL_STATE;
if (valid && !blockNumber) return LOADING_CALL_STATE;
if (!contractInterface || !fragment || !latestBlockNumber)
return LOADING_CALL_STATE;
const success = data && data.length > 2;
const syncing = (blockNumber ?? 0) < latestBlockNumber;
let result: Result | undefined = undefined;
if (success && data) {
try {
result = contractInterface.decodeFunctionResult(fragment, data);
} catch (error) {
console.debug('Result data parsing failed', fragment, data);
return {
valid: true,
loading: false,
error: true,
syncing,
result,
};
}
}
return {
valid: true,
loading: false,
syncing,
result: result,
error: !success,
};
}
Example #2
Source File: hooks.ts From cheeseswap-interface with GNU General Public License v3.0 | 6 votes |
function toCallState(
callResult: CallResult | undefined,
contractInterface: Interface | undefined,
fragment: FunctionFragment | undefined,
latestBlockNumber: number | undefined
): CallState {
if (!callResult) return INVALID_CALL_STATE
const { valid, data, blockNumber } = callResult
if (!valid) return INVALID_CALL_STATE
if (valid && !blockNumber) return LOADING_CALL_STATE
if (!contractInterface || !fragment || !latestBlockNumber) return LOADING_CALL_STATE
const success = data && data.length > 2
const syncing = (blockNumber ?? 0) < latestBlockNumber
let result: Result | undefined = undefined
if (success && data) {
try {
result = contractInterface.decodeFunctionResult(fragment, data)
} catch (error) {
console.debug('Result data parsing failed', fragment, data)
return {
valid: true,
loading: false,
error: true,
syncing,
result
}
}
}
return {
valid: true,
loading: false,
syncing,
result: result,
error: !success
}
}
Example #3
Source File: index.ts From ccip-read with MIT License | 6 votes |
/**
* Adds an interface to the gateway server, with handlers to handle some or all of its functions.
* @param abi The contract ABI to use. This can be in any format that ethers.js recognises, including
* a 'Human Readable ABI', a JSON-format ABI, or an Ethers `Interface` object.
* @param handlers An array of handlers to register against this interface.
*/
add(abi: string | readonly (string | Fragment | JsonFragment)[] | Interface, handlers: Array<HandlerDescription>) {
const abiInterface = toInterface(abi);
for (const handler of handlers) {
const fn = abiInterface.getFunction(handler.type);
this.handlers[Interface.getSighash(fn)] = {
type: fn,
func: handler.func,
};
}
}
Example #4
Source File: multicall.ts From frontend-ui with GNU General Public License v3.0 | 6 votes |
multicall = async (abi: any[], calls: Call[]) => {
const web3 = getWeb3()
const multi = new web3.eth.Contract((MultiCallAbi as unknown) as AbiItem, getMulticallAddress())
const itf = new Interface(abi)
const calldata = calls.map((call) => [call.address.toLowerCase(), itf.encodeFunctionData(call.name, call.params)])
const { returnData } = await multi.methods.aggregate(calldata).call()
const res = returnData.map((call, i) => itf.decodeFunctionResult(calls[i].name, call))
return res
}
Example #5
Source File: abi.ts From snapshot-plugins with MIT License | 6 votes |
export function getABIWriteFunctions(abi: Fragment[]) {
const abiInterface = new Interface(abi);
return (
abiInterface.fragments
// Return only contract's functions
.filter(FunctionFragment.isFunctionFragment)
.map(FunctionFragment.fromObject)
// Return only write functions
.filter(isWriteFunction)
// Sort by name
.sort((a, b) => (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1))
);
}
Example #6
Source File: hooks.ts From sybil-interface with GNU General Public License v3.0 | 6 votes |
export function useMultipleContractSingleData(
addresses: (string | undefined)[],
contractInterface: Interface,
methodName: string,
callInputs?: OptionalMethodInputs,
options?: ListenerOptions
): CallState[] {
const fragment = useMemo(() => contractInterface.getFunction(methodName), [contractInterface, methodName])
const callData: string | undefined = useMemo(
() =>
fragment && isValidMethodArgs(callInputs)
? contractInterface.encodeFunctionData(fragment, callInputs)
: undefined,
[callInputs, contractInterface, fragment]
)
const calls = useMemo(
() =>
fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>((address) => {
return address && callData
? {
address,
callData,
}
: undefined
})
: [],
[addresses, callData, fragment]
)
const results = useCallsData(calls, options)
const latestBlockNumber = useBlockNumber()
return useMemo(() => {
return results.map((result) => toCallState(result, contractInterface, fragment, latestBlockNumber))
}, [fragment, results, contractInterface, latestBlockNumber])
}
Example #7
Source File: abi.ts From snapshot-plugins with MIT License | 6 votes |
export function getContractTransactionData(
abi: string,
method: FunctionFragment,
values: string[]
) {
const contractInterface = new Interface(abi);
const parameterValues = method.inputs.map(extractMethodArgs(values));
return contractInterface.encodeFunctionData(method, parameterValues);
}
Example #8
Source File: AbiParser.ts From useDApp with MIT License | 6 votes |
function makeCallParser(coder: Interface, fragment: FunctionFragment): CallParser {
return {
name: fragment.name,
parseCallData(data: string) {
try {
const decoded = coder.decodeFunctionData(fragment, data)
return fragment.inputs.map((input, i) => parseDecoded(input, decoded[i], i))
} catch {
return parseUnknownCallData(data)
}
},
parseCallResult(data: string) {
try {
if (fragment.outputs) {
const decoded = coder.decodeFunctionResult(fragment, data)
const items = fragment.outputs.map((input, i) => parseDecoded(input, decoded[i], i))
if (items.length === 1) {
return items[0]
} else {
return { type: 'tuple', name: '#0', value: items }
}
} else {
return parseUnknownCallResult(data)
}
} catch {
return parseUnknownCallResult(data)
}
},
}
}
Example #9
Source File: utils.ts From snapshot.js with MIT License | 6 votes |
export async function multicall(
network: string,
provider,
abi: any[],
calls: any[],
options?
) {
const multicallAbi = [
'function aggregate(tuple(address target, bytes callData)[] calls) view returns (uint256 blockNumber, bytes[] returnData)'
];
const multi = new Contract(
networks[network].multicall,
multicallAbi,
provider
);
const itf = new Interface(abi);
try {
const max = options?.limit || 500;
const pages = Math.ceil(calls.length / max);
const promises: any = [];
Array.from(Array(pages)).forEach((x, i) => {
const callsInPage = calls.slice(max * i, max * (i + 1));
promises.push(
multi.aggregate(
callsInPage.map((call) => [
call[0].toLowerCase(),
itf.encodeFunctionData(call[1], call[2])
]),
options || {}
)
);
});
let results: any = await Promise.all(promises);
results = results.reduce((prev: any, [, res]: any) => prev.concat(res), []);
return results.map((call, i) =>
itf.decodeFunctionResult(calls[i][1], call)
);
} catch (e) {
return Promise.reject(e);
}
}
Example #10
Source File: AbiEntry.ts From useDApp with MIT License | 6 votes |
export function toAbiEntry(abi: AbiInput): AbiEntry | undefined {
const coder = new Interface([abi])
const fragment = coder.functions[Object.keys(coder.functions)[0]]
if (!fragment) {
return undefined
}
const selector = coder.getSighash(fragment)
const code = fragment.format(FormatTypes.full)
return { code, coder, fragment, selector }
}
Example #11
Source File: TotalSupply.ts From interface-v2 with GNU General Public License v3.0 | 6 votes |
export function useTotalSupplys(tokens: Token[]): (TokenAmount | undefined)[] {
const tokenAddresses = tokens.map((token) => token.address);
const tokenInterface = new Interface(ERC20_ABI);
const results = useMultipleContractSingleData(
tokenAddresses,
tokenInterface,
'totalSupply',
);
return results.map((result, i) => {
const { result: reserves } = result;
const totalSupply: BigNumber = reserves?.[0];
return totalSupply
? new TokenAmount(tokens[i], totalSupply.toString())
: undefined;
});
}
Example #12
Source File: hooks.ts From luaswap-interface with GNU General Public License v3.0 | 6 votes |
export function useMultipleContractSingleData(
addresses: (string | undefined)[],
contractInterface: Interface,
methodName: string,
callInputs?: OptionalMethodInputs,
options?: ListenerOptions
): CallState[] {
const fragment = useMemo(() => contractInterface.getFunction(methodName), [contractInterface, methodName])
const callData: string | undefined = useMemo(
() =>
fragment && isValidMethodArgs(callInputs)
? contractInterface.encodeFunctionData(fragment, callInputs)
: undefined,
[callInputs, contractInterface, fragment]
)
const calls = useMemo(
() =>
fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>(address => {
return address && callData
? {
address,
callData
}
: undefined
})
: [],
[addresses, callData, fragment]
)
const results = useCallsData(calls, options)
const latestBlockNumber = useBlockNumber()
return useMemo(() => {
return results.map(result => toCallState(result, contractInterface, fragment, latestBlockNumber))
}, [fragment, results, contractInterface, latestBlockNumber])
}
Example #13
Source File: hooks.ts From goose-frontend-amm with GNU General Public License v3.0 | 6 votes |
function toCallState(
callResult: CallResult | undefined,
contractInterface: Interface | undefined,
fragment: FunctionFragment | undefined,
latestBlockNumber: number | undefined
): CallState {
if (!callResult) return INVALID_CALL_STATE
const { valid, data, blockNumber } = callResult
if (!valid) return INVALID_CALL_STATE
if (valid && !blockNumber) return LOADING_CALL_STATE
if (!contractInterface || !fragment || !latestBlockNumber) return LOADING_CALL_STATE
const success = data && data.length > 2
const syncing = (blockNumber ?? 0) < latestBlockNumber
let result: Result | undefined
if (success && data) {
try {
result = contractInterface.decodeFunctionResult(fragment, data)
} catch (error) {
console.error('Result data parsing failed', fragment, data)
return {
valid: true,
loading: false,
error: true,
syncing,
result,
}
}
}
return {
valid: true,
loading: false,
syncing,
result,
error: !success,
}
}
Example #14
Source File: utils.ts From hardhat-deploy with MIT License | 6 votes |
export function mergeABIs(
abis: any[][],
options: {check: boolean; skipSupportsInterface: boolean}
): any[] {
if (abis.length === 0) {
return [];
}
const result: any[] = JSON.parse(JSON.stringify(abis[0]));
for (let i = 1; i < abis.length; i++) {
const abi = abis[i];
for (const fragment of abi) {
const newEthersFragment = Fragment.from(fragment);
// TODO constructor special handling ?
const foundSameSig = result.find((v) => {
const existingEthersFragment = Fragment.from(v);
if (v.type !== fragment.type) {
return false;
}
if (!existingEthersFragment) {
return v.name === fragment.name; // TODO fallback and receive hanlding
}
if (
existingEthersFragment.type === 'constructor' ||
newEthersFragment.type === 'constructor'
) {
return existingEthersFragment.name === newEthersFragment.name;
}
if (newEthersFragment.type === 'function') {
return (
Interface.getSighash(existingEthersFragment as FunctionFragment) ===
Interface.getSighash(newEthersFragment as FunctionFragment)
);
} else if (newEthersFragment.type === 'event') {
return existingEthersFragment.format() === newEthersFragment.format();
} else {
return v.name === fragment.name; // TODO fallback and receive hanlding
}
});
if (foundSameSig) {
if (
options.check &&
!(
options.skipSupportsInterface &&
fragment.name === 'supportsInterface'
)
) {
if (fragment.type === 'function') {
throw new Error(
`function "${fragment.name}" will shadow "${foundSameSig.name}". Please update code to avoid conflict.`
);
}
}
} else {
result.push(fragment);
}
}
}
return result;
}
Example #15
Source File: hooks.ts From vvs-ui with GNU General Public License v3.0 | 6 votes |
export function useMultipleContractSingleData(
addresses: (string | undefined)[],
contractInterface: Interface,
methodName: string,
callInputs?: OptionalMethodInputs,
options?: ListenerOptions,
): CallState[] {
const fragment = useMemo(() => contractInterface.getFunction(methodName), [contractInterface, methodName])
const callData: string | undefined = useMemo(
() =>
fragment && isValidMethodArgs(callInputs)
? contractInterface.encodeFunctionData(fragment, callInputs)
: undefined,
[callInputs, contractInterface, fragment],
)
const calls = useMemo(
() =>
fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>((address) => {
return address && callData
? {
address,
callData,
}
: undefined
})
: [],
[addresses, callData, fragment],
)
const results = useCallsData(calls, options)
const { currentBlock } = useBlock()
return useMemo(() => {
return results.map((result) => toCallState(result, contractInterface, fragment, currentBlock))
}, [fragment, results, contractInterface, currentBlock])
}
Example #16
Source File: hooks.ts From cuiswap with GNU General Public License v3.0 | 6 votes |
function toCallState(
callResult: CallResult | undefined,
contractInterface: Interface | undefined,
fragment: FunctionFragment | undefined,
latestBlockNumber: number | undefined
): CallState {
if (!callResult) return INVALID_CALL_STATE
const { valid, data, blockNumber } = callResult
if (!valid) return INVALID_CALL_STATE
if (valid && !blockNumber) return LOADING_CALL_STATE
if (!contractInterface || !fragment || !latestBlockNumber) return LOADING_CALL_STATE
const success = data && data.length > 2
const syncing = (blockNumber ?? 0) < latestBlockNumber
let result: Result | undefined = undefined
if (success && data) {
try {
result = contractInterface.decodeFunctionResult(fragment, data)
} catch (error) {
console.debug('Result data parsing failed', fragment, data)
return {
valid: true,
loading: false,
error: true,
syncing,
result
}
}
}
return {
valid: true,
loading: false,
syncing,
result: result,
error: !success
}
}
Example #17
Source File: initializer-data.ts From openzeppelin-upgrades with MIT License | 6 votes |
export function getInitializerData(
contractInterface: Interface,
args: unknown[],
initializer?: string | false,
): string {
if (initializer === false) {
return '0x';
}
const allowNoInitialization = initializer === undefined && args.length === 0;
initializer = initializer ?? 'initialize';
try {
const fragment = contractInterface.getFunction(initializer);
return contractInterface.encodeFunctionData(fragment, args);
} catch (e: unknown) {
if (e instanceof Error) {
if (allowNoInitialization && e.message.includes('no matching function')) {
return '0x';
}
}
throw e;
}
}
Example #18
Source File: hooks.ts From goose-frontend-amm with GNU General Public License v3.0 | 6 votes |
export function useMultipleContractSingleData(
addresses: (string | undefined)[],
contractInterface: Interface,
methodName: string,
callInputs?: OptionalMethodInputs,
options?: ListenerOptions
): CallState[] {
const fragment = useMemo(() => contractInterface.getFunction(methodName), [contractInterface, methodName])
const callData: string | undefined = useMemo(
() =>
fragment && isValidMethodArgs(callInputs)
? contractInterface.encodeFunctionData(fragment, callInputs)
: undefined,
[callInputs, contractInterface, fragment]
)
const calls = useMemo(
() =>
fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>((address) => {
return address && callData
? {
address,
callData,
}
: undefined
})
: [],
[addresses, callData, fragment]
)
const results = useCallsData(calls, options)
const latestBlockNumber = useBlockNumber()
return useMemo(() => {
return results.map((result) => toCallState(result, contractInterface, fragment, latestBlockNumber))
}, [fragment, results, contractInterface, latestBlockNumber])
}
Example #19
Source File: hooks.ts From limit-orders-lib with GNU General Public License v3.0 | 6 votes |
function toCallState(
callResult: CallResult | undefined,
contractInterface: Interface | undefined,
fragment: FunctionFragment | undefined,
latestBlockNumber: number | undefined
): CallState {
if (!callResult) return INVALID_CALL_STATE;
const { valid, data, blockNumber } = callResult;
if (!valid) return INVALID_CALL_STATE;
if (valid && !blockNumber) return LOADING_CALL_STATE;
if (!contractInterface || !fragment || !latestBlockNumber)
return LOADING_CALL_STATE;
const success = data && data.length > 2;
const syncing = (blockNumber ?? 0) < latestBlockNumber;
let result: Result | undefined = undefined;
if (success && data) {
try {
result = contractInterface.decodeFunctionResult(fragment, data);
} catch (error) {
console.debug("Result data parsing failed", fragment, data);
return {
valid: true,
loading: false,
error: true,
syncing,
result,
};
}
}
return {
valid: true,
loading: false,
syncing,
result: result,
error: !success,
};
}
Example #20
Source File: hooks.ts From luaswap-interface with GNU General Public License v3.0 | 6 votes |
function toCallState(
callResult: CallResult | undefined,
contractInterface: Interface | undefined,
fragment: FunctionFragment | undefined,
latestBlockNumber: number | undefined
): CallState {
if (!callResult) return INVALID_CALL_STATE
const { valid, data, blockNumber } = callResult
if (!valid) return INVALID_CALL_STATE
if (valid && !blockNumber) return LOADING_CALL_STATE
if (!contractInterface || !fragment || !latestBlockNumber) return LOADING_CALL_STATE
const success = data && data.length > 2
const syncing = (blockNumber ?? 0) < latestBlockNumber
let result: Result | undefined = undefined
if (success && data) {
try {
result = contractInterface.decodeFunctionResult(fragment, data)
} catch (error) {
console.debug('Result data parsing failed', fragment, data)
return {
valid: true,
loading: false,
error: true,
syncing,
result
}
}
}
return {
valid: true,
loading: false,
syncing,
result: result,
error: !success
}
}
Example #21
Source File: hooks.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
export function useMultipleContractSingleData(
addresses: (string | undefined)[],
contractInterface: Interface,
methodName: string,
callInputs?: OptionalMethodInputs,
options?: ListenerOptions,
): CallState[] {
const fragment = useMemo(() => contractInterface.getFunction(methodName), [contractInterface, methodName])
const callData: string | undefined = useMemo(
() =>
fragment && isValidMethodArgs(callInputs)
? contractInterface.encodeFunctionData(fragment, callInputs)
: undefined,
[callInputs, contractInterface, fragment],
)
const calls = useMemo(
() =>
fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>((address) => {
return address && callData
? {
address,
callData,
}
: undefined
})
: [],
[addresses, callData, fragment],
)
const results = useCallsData(calls, options)
const latestBlockNumber = useBlockNumber()
return useMemo(() => {
return results.map((result) => toCallState(result, contractInterface, fragment, latestBlockNumber))
}, [fragment, results, contractInterface, latestBlockNumber])
}
Example #22
Source File: Reserves.ts From panther-frontend-dex with GNU General Public License v3.0 | 5 votes |
PAIR_INTERFACE = new Interface(IUniswapV2PairABI)
Example #23
Source File: Reserves.ts From pancake-swap-exchange-testnet with GNU General Public License v3.0 | 5 votes |
PAIR_INTERFACE = new Interface(IUniswapV2PairABI)
Example #24
Source File: erc20.ts From mozartfinance-swap-interface with GNU General Public License v3.0 | 5 votes |
ERC20_INTERFACE = new Interface(ERC20_ABI)
Example #25
Source File: tokenSubscriptionsUpdater.ts From mStable-apps with GNU Lesser General Public License v3.0 | 5 votes |
contractInterface = (() => {
const abi = [
{
constant: true,
inputs: [
{
internalType: 'address',
name: 'account',
type: 'address',
},
],
name: 'balanceOf',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
},
],
payable: false,
stateMutability: 'view',
type: 'function',
},
{
constant: true,
inputs: [
{
internalType: 'address',
name: 'owner',
type: 'address',
},
{
internalType: 'address',
name: 'spender',
type: 'address',
},
],
name: 'allowance',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
},
],
payable: false,
stateMutability: 'view',
type: 'function',
},
]
return new Interface(abi) as unknown as IERC20['interface']
})()
Example #26
Source File: decoder.ts From snapshot-plugins with MIT License | 5 votes |
export class InterfaceDecoder extends Interface {
public decodeFunction(
data: string,
fragmentOrName?: string | Fragment | JsonFragment
) {
const fragment = this.getMethodFragment(data, fragmentOrName);
if (!FunctionFragment.isFunctionFragment(fragment)) {
throw new Error(
`could not resolved to a function fragment fragmentOrName: ${fragmentOrName}`
);
}
const functionFragment = FunctionFragment.fromObject(fragment);
const decodedValues = this.decodeFunctionData(functionFragment.name, data);
return functionFragment.inputs.reduce((acc, parameter, index) => {
const value = decodedValues[index];
const formattedValue = this.formatParameter(parameter, value);
acc.push(formattedValue);
if (parameter.name) {
acc[parameter.name] = formattedValue;
}
return acc;
}, [] as string[]);
}
public getMethodFragment(
data: string,
fragmentOrName?: string | Fragment | JsonFragment
): Fragment | JsonFragment {
if (typeof fragmentOrName === 'string') {
return this.getFunction(fragmentOrName);
} else if (!fragmentOrName) {
const signature = data.substr(0, 10);
return this.getFunction(signature);
}
return fragmentOrName;
}
private formatParameter(parameter, value, deep = 0): string {
if (isArrayParameter(parameter.baseType)) {
return this.formatArrayValue(parameter.arrayChildren, value, deep);
}
return this.formatValue(parameter.type, value);
}
private formatArrayValue(paramType, value, deep = 0) {
const formattedValues = value.map((paramValue) =>
this.formatParameter(paramType, paramValue, deep + 1)
);
if (deep) return formattedValues;
return JSON.stringify(formattedValues);
}
private formatValue(type, value): string {
return value.toString();
}
}
Example #27
Source File: index.ts From ccip-read with MIT License | 5 votes |
CCIP_READ_INTERFACE = new Interface([
'error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData)',
'function callback(bytes memory result, bytes memory extraData)',
])
Example #28
Source File: abi.ts From snapshot-plugins with MIT License | 5 votes |
export function getAbiFirstFunctionName(abi: ABI): string {
const abiInterface = new Interface(abi);
return abiInterface.fragments[0].name;
}
Example #29
Source File: Reserves.ts From pancakeswap-testnet with GNU General Public License v3.0 | 5 votes |
PAIR_INTERFACE = new Interface(IUniswapV2PairABI)