Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for ABI #1045

Merged
merged 9 commits into from
Jan 25, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/near-api-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"browser": "lib/browser-index.js",
"types": "lib/index.d.ts",
"dependencies": {
"ajv": "^8.11.2",
"ajv-formats": "^2.1.1",
"bn.js": "5.2.1",
"borsh": "^0.7.0",
"bs58": "^4.0.0",
Expand All @@ -19,6 +21,7 @@
"http-errors": "^1.7.2",
"js-sha256": "^0.9.0",
"mustache": "^4.0.0",
"near-abi": "git@github.com:near/near-abi-js.git",
"node-fetch": "^2.6.1",
"text-encoding-utf-8": "^1.0.2",
"tweetnacl": "^1.0.1"
Expand Down Expand Up @@ -76,4 +79,4 @@
"browser-exports.js"
],
"author": "NEAR Inc"
}
}
104 changes: 90 additions & 14 deletions packages/near-api-js/src/contract.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import BN from 'bn.js';
import depd from 'depd';
import { AbiFunction, AbiFunctionKind, AbiJsonParameter, AbiRoot, AbiSerializationType } from 'near-abi';
import { Account } from './account';
import { getTransactionLastResult } from './providers';
import { PositionalArgsError, ArgumentTypeError } from './utils/errors';
import { PositionalArgsError, ArgumentTypeError, UnsupportedSerializationError, UnknownArgumentError, ArgumentSchemaError } from './utils/errors';

// Makes `function.name` return given name
function nameFunction(name: string, body: (args?: any[]) => any) {
Expand All @@ -13,6 +16,27 @@ function nameFunction(name: string, body: (args?: any[]) => any) {
}[name];
}

function validateArguments(args: object, params: AbiJsonParameter[], ajv: Ajv, abi: AbiRoot) {
if (isObject(args)) {
itegulov marked this conversation as resolved.
Show resolved Hide resolved
for (const p of params) {
const arg = args[p.name];
const typeSchema = p.type_schema;
typeSchema.definitions = abi.body.root_schema.definitions;
const validate = ajv.compile(typeSchema);
if (!validate(arg)) {
throw new ArgumentSchemaError(p.name, validate.errors);
}
}
// Check there are no extra unknown arguments passed
for (const argName of Object.keys(args)) {
const param = params.find((p) => p.name === argName);
if (!param) {
throw new UnknownArgumentError(argName, params.map((p) => p.name));
}
}
}
}

const isUint8Array = (x: any) =>
x && x.byteLength !== undefined && x.byteLength === x.length;

Expand Down Expand Up @@ -42,6 +66,11 @@ export interface ContractMethods {
* @see {@link account!Account#viewFunction}
*/
viewMethods: string[];

/**
* ABI defining this contract's interface.
*/
abi: AbiRoot;
}

/**
Expand Down Expand Up @@ -90,45 +119,92 @@ export class Contract {
constructor(account: Account, contractId: string, options: ContractMethods) {
this.account = account;
this.contractId = contractId;
const { viewMethods = [], changeMethods = [] } = options;
viewMethods.forEach((methodName) => {
Object.defineProperty(this, methodName, {
const { viewMethods = [], changeMethods = [], abi: abiRoot } = options;
andy-haynes marked this conversation as resolved.
Show resolved Hide resolved

let viewMethodsWithAbi = viewMethods.map((name) => ({ name, abi: null as AbiFunction }));
let changeMethodsWithAbi = changeMethods.map((name) => ({ name, abi: null }));
if (abiRoot) {
const abiViewMethods = abiRoot.body.functions
.filter((m) => m.kind === AbiFunctionKind.View)
.map((m) => ({ name: m.name, abi: m }));
const abiChangeMethods = abiRoot.body.functions
.filter((methodAbi) => methodAbi.kind === AbiFunctionKind.Call)
.map((methodAbi) => ({ name: methodAbi.name, abi: methodAbi }));
viewMethodsWithAbi = viewMethodsWithAbi.concat(abiViewMethods);
changeMethodsWithAbi = changeMethodsWithAbi.concat(abiChangeMethods);
}

// Strict mode is disabled for now as it complains about unknown formats. We need to
// figure out if we want to support a fixed set of formats. `uint32` and `uint64`
// are added explicitly just to reduce the amount of warnings as these are very popular
// types.
const ajv = new Ajv({
strictSchema: false,
formats: {
uint32: true,
uint64: true
}
});
addFormats(ajv);
itegulov marked this conversation as resolved.
Show resolved Hide resolved

viewMethodsWithAbi.forEach(({ name, abi }) => {
Object.defineProperty(this, name, {
writable: false,
enumerable: true,
value: nameFunction(methodName, async (args: object = {}, options = {}, ...ignored) => {
value: nameFunction(name, async (args: object = {}, options = {}, ...ignored) => {
if (ignored.length || !(isObject(args) || isUint8Array(args)) || !isObject(options)) {
throw new PositionalArgsError();
}

if (abi) {
if (abi.params && abi.params.serialization_type !== AbiSerializationType.Json) {
andy-haynes marked this conversation as resolved.
Show resolved Hide resolved
throw new UnsupportedSerializationError(abi.name, abi.params.serialization_type);
}

if (abi.result && abi.result.serialization_type !== AbiSerializationType.Json) {
throw new UnsupportedSerializationError(abi.name, abi.params.serialization_type);
}

// Safe cast as we have asserted that root ABI contains exclusively JSON parameters
const params = abi ? abi.params.args as AbiJsonParameter[] : [];
validateArguments(args, params, ajv, abiRoot);
}

return this.account.viewFunction({
contractId: this.contractId,
methodName,
methodName: name,
args,
...options,
});
})
});
});
changeMethods.forEach((methodName) => {
Object.defineProperty(this, methodName, {
changeMethodsWithAbi.forEach(({ name, abi }) => {
Object.defineProperty(this, name, {
writable: false,
enumerable: true,
value: nameFunction(methodName, async (...args: any[]) => {
value: nameFunction(name, async (...args: any[]) => {
if (args.length && (args.length > 3 || !(isObject(args[0]) || isUint8Array(args[0])))) {
throw new PositionalArgsError();
}

if(args.length > 1 || !(args[0] && args[0].args)) {
if (args.length > 1 || !(args[0] && args[0].args)) {
const deprecate = depd('contract.methodName(args, gas, amount)');
deprecate('use `contract.methodName({ args, gas?, amount?, callbackUrl?, meta? })` instead');
return this._changeMethod({
methodName,
args[0] = {
args: args[0],
gas: args[1],
amount: args[2]
});
};
}

if (abi) {
// Safe cast as we have asserted that root ABI contains exclusively JSON parameters
const params = abi.params.args as AbiJsonParameter[];
validateArguments(args[0].args, params, ajv, abiRoot);
}

return this._changeMethod({ methodName, ...args[0] });
return this._changeMethod({ methodName: name, ...args[0] });
})
});
});
Expand Down
24 changes: 22 additions & 2 deletions packages/near-api-js/src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ErrorObject } from 'ajv';

export class PositionalArgsError extends Error {
constructor() {
super('Contract method calls expect named arguments wrapped in object, e.g. { argName1: argValue1, argName2: argValue2 }');
Expand Down Expand Up @@ -28,7 +30,25 @@ export class ErrorContext {
}

export function logWarning(...args: any[]): void {
if (!process.env['NEAR_NO_LOGS']){
if (!process.env['NEAR_NO_LOGS']) {
console.warn(...args);
}
}
}

export class UnsupportedSerializationError extends Error {
constructor(methodName: string, serializationType: string) {
super(`Contract method '${methodName}' is using an unsupported serialization type ${serializationType}`);
}
}

export class UnknownArgumentError extends Error {
constructor(actualArgName: string, expectedArgNames: string[]) {
super(`Unrecognized argument '${actualArgName}', expected '${JSON.stringify(expectedArgNames)}'`);
}
}

export class ArgumentSchemaError extends Error {
constructor(argName: string, errors: ErrorObject[]) {
super(`Argument '${argName}' does not conform to the specified ABI schema: '${JSON.stringify(errors)}'`);
}
}
Loading