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 a new option to customize known function signature #108

Draft
wants to merge 3 commits into
base: ethers-refactor
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
24 changes: 14 additions & 10 deletions src/evaluator/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @module radspec/evaluator
*/

import { ethers, BigNumber } from 'ethers'
import { BigNumber, providers as ethersProvider, utils as ethersUtils } from 'ethers'

import types from '../types'
import HelperManager from '../helpers/HelperManager'
Expand All @@ -27,10 +27,10 @@ class TypedValue {
}

if (this.type === 'address') {
if (!ethers.utils.isAddress(this.value)) {
if (!ethersUtils.isAddress(this.value)) {
throw new Error(`Invalid address "${this.value}"`)
}
this.value = ethers.utils.getAddress(this.value)
this.value = ethersUtils.getAddress(this.value)
}
}

Expand All @@ -52,7 +52,8 @@ class TypedValue {
* @param {radspec/Bindings} bindings An object of bindings and their values
* @param {?Object} options An options object
* @param {?Object} options.availablehelpers Available helpers
* @param {?ethers.providers.Provider} options.provider EIP 1193 provider
* @param {?Object} options.availableFunctions Available function signatures
* @param {?ethersProvider.Provider} options.provider EIP 1193 provider
* @param {?string} options.to The destination address for this expression's transaction
* @property {radspec/parser/AST} ast
* @property {radspec/Bindings} bindings
Expand All @@ -61,17 +62,18 @@ export class Evaluator {
constructor (
ast,
bindings,
{ availableHelpers = {}, provider, from, to, value = '0', data } = {}
{ availableHelpers = {}, availableFunctions = {}, provider, from, to, value = '0', data } = {}
) {
this.ast = ast
this.bindings = bindings
this.provider =
provider || new ethers.providers.WebSocketProvider(DEFAULT_ETH_NODE)
provider || new ethersProvider.WebSocketProvider(DEFAULT_ETH_NODE)
this.from = from && new TypedValue('address', from)
this.to = to && new TypedValue('address', to)
this.value = new TypedValue('uint', BigNumber.from(value))
this.data = data && new TypedValue('bytes', data)
this.helpers = new HelperManager(availableHelpers)
this.functions = availableFunctions
}

/**
Expand Down Expand Up @@ -242,7 +244,7 @@ export class Evaluator {

if (target.type !== 'bytes20' && target.type !== 'address') {
this.panic('Target of call expression was not an address')
} else if (!ethers.utils.isAddress(target.value)) {
} else if (!ethersUtils.isAddress(target.value)) {
this.panic(`Invalid address "${this.value}"`)
}

Expand Down Expand Up @@ -271,7 +273,7 @@ export class Evaluator {
stateMutability: 'view'
}
]
const ethersInterface = new ethers.utils.Interface(abi)
const ethersInterface = new ethersUtils.Interface(abi)

const txData = ethersInterface.encodeFunctionData(
node.callee,
Expand All @@ -298,7 +300,8 @@ export class Evaluator {
const inputs = await this.evaluateNodes(node.inputs)
const result = await this.helpers.execute(helperName, inputs, {
provider: this.provider,
evaluator: this
evaluator: this,
functions: this.functions
})

return new TypedValue(result.type, result.value)
Expand Down Expand Up @@ -368,7 +371,8 @@ export class Evaluator {
* @param {radspec/Bindings} bindings An object of bindings and their values
* @param {?Object} options An options object
* @param {?Object} options.availablehelpers Available helpers
* @param {?ethers.providers.Provider} options.provider EIP 1193 provider
* @param {?Object} options.availableFunctions Available function signatures
* @param {?ethersProvider.Provider} options.provider EIP 1193 provider
* @param {?string} options.to The destination address for this expression's transaction
* @return {string}
*/
Expand Down
7 changes: 4 additions & 3 deletions src/helpers/HelperManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,14 @@ export default class HelperManager {
* @param {string} helper Helper name
* @param {Array<radspec/evaluator/TypedValue>} inputs
* @param {Object} config Configuration for running helper
* @param {ethers.providers.Provider} config.provider Current provider
* @param {ethersProvider.Provider} config.provider Current provider
* @param {radspec/evaluator/Evaluator} config.evaluator Current evaluator
* @param {Object} config.functions Current function signatures
* @return {Promise<radspec/evaluator/TypedValue>}
*/
execute (helper, inputs, { provider, evaluator }) {
execute (helper, inputs, { provider, evaluator, functions }) {
inputs = inputs.map((input) => input.value) // pass values directly
return this.availableHelpers[helper](provider, evaluator)(...inputs)
return this.availableHelpers[helper](provider, evaluator, functions)(...inputs)
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/fromHex.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethers, BigNumber } from 'ethers'
import { BigNumber, utils as ethersUtils } from 'ethers'

export default () =>
/**
Expand All @@ -13,5 +13,5 @@ export default () =>
value:
to === 'number'
? BigNumber.from(hex).toNumber()
: ethers.utils.toUtf8String(hex)
: ethersUtils.toUtf8String(hex)
})
6 changes: 3 additions & 3 deletions src/helpers/lib/methodRegistry.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// From: https://github.com/danfinlay/eth-method-registry
import { ethers } from 'ethers'
import { Contract, providers as ethersProviders } from 'ethers'

import { DEFAULT_ETH_NODE } from '../../defaults'

Expand All @@ -15,7 +15,7 @@ const REGISTRY_MAP = {
export default class MethodRegistry {
constructor (opts = {}) {
this.provider =
opts.provider || new ethers.providers.WebSocketProvider(DEFAULT_ETH_NODE)
opts.provider || new ethersProviders.WebSocketProvider(DEFAULT_ETH_NODE)
this.registryAddres = opts.registry || REGISTRY_MAP[opts.network]
}

Expand All @@ -24,7 +24,7 @@ export default class MethodRegistry {
throw new Error('No method registry found for the network.')
}

this.registry = new ethers.Contract(
this.registry = new Contract(
this.registryAddres,
REGISTRY_LOOKUP_ABI,
this.provider
Expand Down
44 changes: 24 additions & 20 deletions src/helpers/radspec.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { ethers } from 'ethers'
import { utils as ethersUtils } from 'ethers'

import MethodRegistry from './lib/methodRegistry'
import { evaluateRaw } from '../lib/'
import { knownFunctions } from '../data/'
import { DEFAULT_API_4BYTES } from '../defaults'

const makeUnknownFunctionNode = (methodId) => ({
Expand All @@ -11,7 +10,7 @@ const makeUnknownFunctionNode = (methodId) => ({
})

const parse = (signature) => {
const fragment = ethers.utils.FunctionFragment.from(signature)
const fragment = ethersUtils.FunctionFragment.from(signature)

return {
name:
Expand All @@ -27,40 +26,40 @@ const parse = (signature) => {
}

// Hash signature with Ethereum Identity and silce bytes
const getSigHah = (sig) => ethers.utils.hexDataSlice(ethers.utils.id(sig), 0, 4)
const getSigHah = (sig) => ethersUtils.hexDataSlice(ethersUtils.id(sig), 0, 4)

// Convert from the knownFunctions data format into the needed format
// Input: { "signature(type1,type2)": "Its radspec string", ... }
// Output: { "0xabcdef12": { "fragment": FunctionFragment, "source": "Its radspec string" }, ...}
const processFunctions = (functions) =>
Object.keys(functions).reduce((acc, key) => {
const fragment = ethers.utils.FunctionFragment.from(key)
const fragment = ethersUtils.FunctionFragment.from(key)
return {
[getSigHah(fragment.format())]: { source: functions[key], fragment },
...acc
}
}, {})

export default (provider, evaluator) =>
export default (provider, evaluator, functions) =>
/**
* Interpret calldata using radspec recursively. If the function signature is not in the package's known
* functions, it fallbacks to looking for the function name using github.com/parity-contracts/signature-registry
* functions, it fallbacks to looking for the function name using github.com/parity-contracts/signature-registry and finally using 4bytes API
*
* @param {address} addr The target address of the call
* @param {bytes} data The calldata of the call
* @param {string} [registryAddress] The registry address to lookup descriptions
* @return {Promise<radspec/evaluator/TypedValue>}
*/
async (addr, data, registryAddress) => {
const functions = processFunctions(knownFunctions)
const processedFunctions = processFunctions(functions)

if (data.length < 10) {
return makeUnknownFunctionNode(data)
}

// Get method ID
const methodId = data.substr(0, 10)
const fn = functions[methodId]
const fn = processedFunctions[methodId]

// If function is not a known function
if (!fn) {
Expand All @@ -80,25 +79,29 @@ export default (provider, evaluator) =>
value: name // TODO: should we decode and print the arguments as well?
}
} catch {
try {
// Try fetching 4bytes API
const { results } = await ethers.utils.fetchJson(
`${DEFAULT_API_4BYTES}?hex_signature=${methodId}`
)
if (Array.isArray(results) && results.length > 0) {
const { name } = parse(results[0].text_signature)
return {
type: 'string',
value: name
const { results } = await ethersUtils.fetchJson({
url: `${DEFAULT_API_4BYTES}?hex_signature=${methodId}`,
timeout: 3000
})
if (Array.isArray(results) && results.length > 0) {
const { name } = parse(results[0].text_signature)
return {
type: 'string',
value: name
}
}
} catch {
// Fallback to unknown function
return makeUnknownFunctionNode(methodId)
}
// Fallback to unknown function
return makeUnknownFunctionNode(methodId)
}
}
// If the function was found in local radspec registry. Decode and evaluate.
const { source, fragment } = fn

const ethersInterface = new ethers.utils.Interface([fragment])
const ethersInterface = new ethersUtils.Interface([fragment])

// Decode parameters
const args = ethersInterface.decodeFunctionData(fragment.name, data)
Expand All @@ -119,6 +122,7 @@ export default (provider, evaluator) =>
value: await evaluateRaw(source, parameters, {
provider,
availableHelpers: evaluator.helpers.getHelpers(),
availableFunctions: functions,
to: addr
})
}
Expand Down
8 changes: 4 additions & 4 deletions src/helpers/tokenAmount.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethers, BigNumber } from 'ethers'
import { BigNumber, Contract, utils as ethersUtils } from 'ethers'

import {
ERC20_SYMBOL_BYTES32_ABI,
Expand Down Expand Up @@ -30,7 +30,7 @@ export default (provider) =>
symbol = 'ETH'
}
} else {
let token = new ethers.Contract(
let token = new Contract(
tokenAddress,
ERC20_SYMBOL_DECIMALS_ABI,
provider
Expand All @@ -42,13 +42,13 @@ export default (provider) =>
symbol = (await token.symbol()) || ''
} catch (err) {
// Some tokens (e.g. DS-Token) use bytes32 for their symbol()
token = new ethers.Contract(
token = new Contract(
tokenAddress,
ERC20_SYMBOL_BYTES32_ABI,
provider
)
symbol = (await token.symbol()) || ''
symbol = symbol && ethers.utils.toUtf8String(symbol)
symbol = symbol && ethersUtils.toUtf8String(symbol)
}
}
}
Expand Down
14 changes: 10 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { knownFunctions } from './data'

/**
* @typedef {Object} Binding
* @property {string} type The type of the binding (a valid Radspec type)
Expand All @@ -10,7 +12,7 @@
/**
* @module radspec
*/
import { ethers } from 'ethers'
import { utils as ethersUtils } from 'ethers'
import { defaultHelpers } from './helpers'
import { evaluateRaw } from './lib'

Expand Down Expand Up @@ -38,13 +40,14 @@ import { evaluateRaw } from './lib'
* @param {string} call.transaction.to The destination address for this transaction
* @param {string} call.transaction.data The transaction data
* @param {?Object} options An options object
* @param {?ethers.providers.Provider} options.provider EIP 1193 provider
* @param {?ethersProvider.Provider} options.provider EIP 1193 provider
* @param {?Object} options.userHelpers User defined helpers
* @param {?Object} options.userFunctions User defined function signatures
* @return {Promise<string>} The result of the evaluation
*/
function evaluate (source, call, { userHelpers = {}, ...options } = {}) {
function evaluate (source, call, { userHelpers = {}, userFunctions = {}, ...options } = {}) {
// Create ethers interface object
const ethersInterface = new ethers.utils.Interface(call.abi)
const ethersInterface = new ethersUtils.Interface(call.abi)

// Parse as an ethers TransactionDescription
const { args, functionFragment } = ethersInterface.parseTransaction(
Expand All @@ -64,13 +67,16 @@ function evaluate (source, call, { userHelpers = {}, ...options } = {}) {

const availableHelpers = { ...defaultHelpers, ...userHelpers }

const availableFunctions = { ...knownFunctions, ...userFunctions }

// Get additional options
const { from, to, value, data } = call.transaction

// Evaluate expression with bindings from the transaction data
return evaluateRaw(source, parameters, {
...options,
availableHelpers,
availableFunctions,
from,
to,
value,
Expand Down
Loading