@ethersproject/abi#ParamType TypeScript Examples
The following examples show how to use
@ethersproject/abi#ParamType.
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: function-fragment.ts From fuels-ts with Apache License 2.0 | 6 votes |
static fromObject(value: JsonAbiFragment): FunctionFragment {
const { inputs = [], outputs = [] } = value;
const params = {
type: 'function',
name: value.name,
// TODO: Remove `as any`s when forc doesn't output nulls (https://github.com/FuelLabs/sway/issues/926)
inputs: (inputs as any).map(ParamType.fromObject),
outputs: (outputs as any).map(ParamType.fromObject),
};
return new FunctionFragment(params);
}
Example #2
Source File: function-fragment.ts From fuels-ts with Apache License 2.0 | 6 votes |
/**
* An override for the `format` method of Ethers' ParamType to handle Fuel/Ethereum ABI incompatibilities
*/
function formatOverride(this: ParamType, format?: string): string {
if (!format || format === FormatTypes.sighash) {
const structMatch = structRegEx.exec(this.type)?.groups;
if (structMatch) {
return `s${this.format(format)}`;
}
const arrayMatch = arrayRegEx.exec(this.type)?.groups;
if (arrayMatch) {
return `[${arrayMatch.item}; ${arrayMatch.length}]`;
}
}
return this.format(format);
}
Example #3
Source File: utilities.ts From fuels-ts with Apache License 2.0 | 6 votes |
export function filterEmptyParams(types: ReadonlyArray<string | ParamType>) {
return types.filter((t) => (t as Readonly<ParamType>)?.type !== '()' && t !== '()');
}
Example #4
Source File: AbiParser.ts From useDApp with MIT License | 6 votes |
function parseDecoded(t: ParamType, value: any, index: number): ParsedValue {
let type: any = t.baseType
if (type.startsWith('uint') || type.startsWith('int')) {
type = 'number'
value = value.toString()
} else if (type.startsWith('bytes')) {
type = 'bytes'
value = normalizeHex(value)
} else if (type === 'bool') {
type = 'boolean'
} else if (type === 'array') {
const array = []
for (let i = 0; i < value.length; i++) {
array.push(parseDecoded(t.arrayChildren, value[i], i))
}
value = array
} else if (type === 'tuple') {
const array = []
for (let i = 0; i < value.length; i++) {
array.push(parseDecoded(t.components[i], value[i], i))
}
value = array
}
return { type, name: t.name ?? `#${index}`, value }
}
Example #5
Source File: abi.ts From ethers-multicall with MIT License | 6 votes |
public static encode(name: string, inputs: ParamType[], params: any[]) {
const functionSignature = getFunctionSignature(name, inputs);
const functionHash = keccak256(toUtf8Bytes(functionSignature));
const functionData = functionHash.substring(2, 10);
const abiCoder = new AbiCoder();
const argumentString = abiCoder.encode(inputs, params);
const argumentData = argumentString.substring(2);
const inputData = `0x${functionData}${argumentData}`;
return inputData;
}
Example #6
Source File: abi.ts From ethers-multicall with MIT License | 6 votes |
function getFunctionSignature(name: string, inputs: ParamType[]) {
const types = [];
for (const input of inputs) {
if (input.type === 'tuple') {
const tupleString = getFunctionSignature('', input.components);
types.push(tupleString);
continue;
}
if (input.type === 'tuple[]') {
const tupleString = getFunctionSignature('', input.components);
const arrayString = `${tupleString}[]`;
types.push(arrayString);
continue;
}
types.push(input.type);
}
const typeString = types.join(',');
const functionSignature = `${name}(${typeString})`;
return functionSignature;
}
Example #7
Source File: abi.ts From snapshot-plugins with MIT License | 6 votes |
function extractMethodArgs(values: string[]) {
return (param: ParamType, index) => {
const value = values[index];
if (isArrayParameter(param.baseType)) {
return JSON.parse(value);
}
return value;
};
}
Example #8
Source File: main.ts From squid with GNU General Public License v3.0 | 6 votes |
// taken from: https://github.com/ethers-io/ethers.js/blob/948f77050dae884fe88932fd88af75560aac9d78/packages/cli/src.ts/typescript.ts#L10
function getType(param: ParamType, flexible?: boolean): string {
if (param.type === "address" || param.type === "string") { return "string"; }
if (param.type === "bool") { return "boolean" }
if (param.type.substring(0, 5) === "bytes") {
if (flexible) {
return "string | ethers.utils.BytesLike";
}
return "string"
}
let match = param.type.match(/^(u?int)([0-9]+)$/)
if (match) {
if (flexible) {
return "ethers.BigNumberish";
}
if (parseInt(match[2]) < 53) { return 'number'; }
return 'ethers.BigNumber';
}
if (param.baseType === "array") {
return "Array<" + getType(param.arrayChildren) + ">";
}
if (param.baseType === "tuple") {
let struct = param.components.map((p, i) => `${p.name || "p_" + i}: ${getType(p, flexible)}`);
return "{ " + struct.join(", ") + " }";
}
throw new Error("unknown type");
}
Example #9
Source File: fragment.ts From fuels-ts with Apache License 2.0 | 5 votes |
readonly inputs: Array<ParamType> = [];
Example #10
Source File: fragment.ts From fuels-ts with Apache License 2.0 | 5 votes |
readonly outputs: Array<ParamType> = [];
Example #11
Source File: abi.ts From ethers-multicall with MIT License | 5 votes |
public static decode(outputs: ParamType[], data: BytesLike) {
const abiCoder = new AbiCoder();
const params = abiCoder.decode(outputs, data);
return params;
}
Example #12
Source File: etherscan.ts From hardhat-deploy with MIT License | 4 votes |
export async function submitSources(
hre: HardhatRuntimeEnvironment,
solcInputsPath: string,
config?: {
contractName?: string;
etherscanApiKey?: string;
license?: string;
fallbackOnSolcInput?: boolean;
forceLicense?: boolean;
sleepBetween?: boolean;
apiUrl?: string;
writePostData?: boolean;
}
): Promise<void> {
config = config || {};
const fallbackOnSolcInput = config.fallbackOnSolcInput;
const licenseOption = config.license;
const forceLicense = config.forceLicense;
const etherscanApiKey = config.etherscanApiKey;
const sleepBetween = config.sleepBetween;
const all = await hre.deployments.all();
const networkName = hre.network.name;
let host = config.apiUrl;
if (!host) {
const chainId = await hre.getChainId();
switch (chainId) {
case '1':
host = 'https://api.etherscan.io';
break;
case '3':
host = 'https://api-ropsten.etherscan.io';
break;
case '4':
host = 'https://api-rinkeby.etherscan.io';
break;
case '5':
host = 'https://api-goerli.etherscan.io';
break;
case '10':
host = 'https://api-optimistic.etherscan.io';
break;
case '42':
host = 'https://api-kovan.etherscan.io';
break;
case '97':
host = 'https://api-testnet.bscscan.com';
break;
case '56':
host = 'https://api.bscscan.com';
break;
case '69':
host = 'https://api-kovan-optimistic.etherscan.io';
break;
case '70':
host = 'https://api.hooscan.com';
break;
case '77':
host = 'https://blockscout.com/poa/sokol';
break;
case '128':
host = 'https://api.hecoinfo.com';
break;
case '137':
host = 'https://api.polygonscan.com';
break;
case '250':
host = 'https://api.ftmscan.com';
break;
case '256':
host = 'https://api-testnet.hecoinfo.com';
break;
case '588':
host = 'https://stardust-explorer.metis.io';
break;
case '1088':
host = 'https://andromeda-explorer.metis.io';
break;
case '1285':
host = 'https://api-moonriver.moonscan.io';
break;
case '80001':
host = 'https://api-testnet.polygonscan.com';
break;
case '4002':
host = 'https://api-testnet.ftmscan.com';
break;
case '42161':
host = 'https://api.arbiscan.io';
break;
case '421611':
host = 'https://api-testnet.arbiscan.io';
break;
case '43113':
host = 'https://api-testnet.snowtrace.io';
break;
case '43114':
host = 'https://api.snowtrace.io';
break;
default:
return logError(
`Network with chainId: ${chainId} not supported. You can specify the url manually via --api-url <url>.`
);
}
}
async function submit(name: string, useSolcInput?: boolean) {
const deployment = all[name];
const {address, metadata: metadataString} = deployment;
const abiResponse = await axios.get(
`${host}/api?module=contract&action=getabi&address=${address}&apikey=${etherscanApiKey}`
);
const {data: abiData} = abiResponse;
let contractABI;
if (abiData.status !== '0') {
try {
contractABI = JSON.parse(abiData.result);
} catch (e) {
logError(e);
return;
}
}
if (contractABI && contractABI !== '') {
log(`already verified: ${name} (${address}), skipping.`);
return;
}
if (!metadataString) {
logError(
`Contract ${name} was deployed without saving metadata. Cannot submit to etherscan, skipping.`
);
return;
}
const metadata = JSON.parse(metadataString);
const compilationTarget = metadata.settings?.compilationTarget;
let contractFilepath;
let contractName;
if (compilationTarget) {
contractFilepath = Object.keys(compilationTarget)[0];
contractName = compilationTarget[contractFilepath];
}
if (!contractFilepath || !contractName) {
return logError(
`Failed to extract contract fully qualified name from metadata.settings.compilationTarget for ${name}. Skipping.`
);
}
const contractNamePath = `${contractFilepath}:${contractName}`;
const contractSourceFile = metadata.sources[contractFilepath].content;
const sourceLicenseType =
extractOneLicenseFromSourceFile(contractSourceFile);
let license = licenseOption;
if (!sourceLicenseType) {
if (!license) {
return logError(
`no license speccified in the source code for ${name} (${contractNamePath}), Please use option --license <SPDX>`
);
}
} else {
if (license && license !== sourceLicenseType) {
if (!forceLicense) {
return logError(
`mismatch for --license option (${licenseOption}) and the one specified in the source code for ${name}.\nLicenses found in source : ${sourceLicenseType}\nYou can use option --force-license to force option --license`
);
}
} else {
license = sourceLicenseType;
if (!getLicenseType(license)) {
return logError(
`license :"${license}" found in source code for ${name} (${contractNamePath}) but this license is not supported by etherscan, list of supported license can be found here : https://etherscan.io/contract-license-types . This tool expect the SPDX id, except for "None" and "UNLICENSED"`
);
}
}
}
const licenseType = getLicenseType(license);
if (!licenseType) {
return logError(
`license :"${license}" not supported by etherscan, list of supported license can be found here : https://etherscan.io/contract-license-types . This tool expect the SPDX id, except for "None" and "UNLICENSED"`
);
}
let solcInput: {
language: string;
settings: any;
sources: Record<string, {content: string}>;
};
if (useSolcInput) {
const solcInputHash = deployment.solcInputHash;
let solcInputStringFromDeployment: string | undefined;
try {
solcInputStringFromDeployment = fs
.readFileSync(path.join(solcInputsPath, solcInputHash + '.json'))
.toString();
} catch (e) {}
if (!solcInputStringFromDeployment) {
logError(
`Contract ${name} was deployed without saving solcInput. Cannot submit to etherscan, skipping.`
);
return;
}
solcInput = JSON.parse(solcInputStringFromDeployment);
} else {
const settings = {...metadata.settings};
delete settings.compilationTarget;
solcInput = {
language: metadata.language,
settings,
sources: {},
};
for (const sourcePath of Object.keys(metadata.sources)) {
const source = metadata.sources[sourcePath];
// only content as this fails otherwise
solcInput.sources[sourcePath] = {
content: source.content,
};
}
}
// Adding Libraries ....
if (deployment.libraries) {
const settings = solcInput.settings;
settings.libraries = settings.libraries || {};
for (const libraryName of Object.keys(deployment.libraries)) {
if (!settings.libraries[contractNamePath]) {
settings.libraries[contractNamePath] = {};
}
settings.libraries[contractNamePath][libraryName] =
deployment.libraries[libraryName];
}
}
const solcInputString = JSON.stringify(solcInput);
logInfo(`verifying ${name} (${address}) ...`);
let constructorArguements: string | undefined;
if (deployment.args) {
const constructor: {inputs: ParamType[]} = deployment.abi.find(
(v) => v.type === 'constructor'
);
if (constructor) {
constructorArguements = defaultAbiCoder
.encode(constructor.inputs, deployment.args)
.slice(2);
}
} else {
logInfo(`no args found, assuming empty constructor...`);
}
const postData: {
[fieldName: string]: string | number | void | undefined; // TODO type
} = {
apikey: etherscanApiKey,
module: 'contract',
action: 'verifysourcecode',
contractaddress: address,
sourceCode: solcInputString,
codeformat: 'solidity-standard-json-input',
contractname: contractNamePath,
compilerversion: `v${metadata.compiler.version}`, // see http://etherscan.io/solcversions for list of support versions
constructorArguements,
licenseType,
};
const formDataAsString = qs.stringify(postData);
const submissionResponse = await axios.request({
url: `${host}/api`,
method: 'POST',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: formDataAsString,
});
const {data: submissionData} = submissionResponse;
let guid: string;
if (submissionData.status === '1') {
guid = submissionData.result;
} else {
logError(
`contract ${name} failed to submit : "${submissionData.message}" : "${submissionData.result}"`,
submissionData
);
writeRequestIfRequested(
config?.writePostData || false,
networkName,
name,
formDataAsString,
postData
);
return;
}
if (!guid) {
logError(`contract submission for ${name} failed to return a guid`);
writeRequestIfRequested(
config?.writePostData || false,
networkName,
name,
formDataAsString,
postData
);
return;
}
async function checkStatus(): Promise<string | undefined> {
// TODO while loop and delay :
const statusResponse = await axios.get(
`${host}/api?apikey=${etherscanApiKey}`,
{
params: {
guid,
module: 'contract',
action: 'checkverifystatus',
},
}
);
const {data: statusData} = statusResponse;
// blockscout seems to return status == 1 in case of failure
// so we check string first
if (statusData.result === 'Pending in queue') {
return undefined;
}
if (statusData.result !== 'Fail - Unable to verify') {
if (statusData.status === '1') {
// console.log(statusData);
return 'success';
}
}
logError(
`Failed to verify contract ${name}: ${statusData.message}, ${statusData.result}`
);
logError(
JSON.stringify(
{
apikey: 'XXXXXX',
module: 'contract',
action: 'verifysourcecode',
contractaddress: address,
sourceCode: '...',
codeformat: 'solidity-standard-json-input',
contractname: contractNamePath,
compilerversion: `v${metadata.compiler.version}`, // see http://etherscan.io/solcversions for list of support versions
constructorArguements,
licenseType,
},
null,
' '
)
);
// logError(JSON.stringify(postData, null, " "));
// logInfo(postData.sourceCode);
return 'failure';
}
logInfo('waiting for result...');
let result;
while (!result) {
await new Promise((resolve) => setTimeout(resolve, 10 * 1000));
result = await checkStatus();
}
if (result === 'success') {
logSuccess(` => contract ${name} is now verified`);
}
if (result === 'failure') {
if (!useSolcInput && fallbackOnSolcInput) {
logInfo(
'Falling back on solcInput. etherscan seems to sometime require full solc-input with all source files, even though this should not be needed. See https://github.com/ethereum/solidity/issues/9573'
);
await submit(name, true);
} else {
writeRequestIfRequested(
config?.writePostData || false,
networkName,
name,
formDataAsString,
postData
);
logInfo(
'Etherscan sometime fails to verify when only metadata sources are given. See https://github.com/ethereum/solidity/issues/9573. You can add the option --solc-input to try with full solc-input sources. This will include all contract source in the etherscan result, even the one not relevant to the contract being verified'
);
}
} else {
writeRequestIfRequested(
config?.writePostData || false,
networkName,
name,
formDataAsString,
postData
);
}
}
if (config.contractName) {
await submit(config.contractName);
} else {
for (const name of Object.keys(all)) {
await submit(name);
if (sleepBetween) {
// sleep between each verification so we don't exceed the API rate limit
await sleep(500);
}
}
}
}