import { ethers } from 'ethers' ; import flatMap from 'lodash/flatMap' ; import { PARAMETER_SHORT_TYPES } from './utils' ; import { ABIParameterType , ABIParameterTypeShort , InputParameter } from './types' ; type TransformationReference = { readonly [ key ] : ( value : any ) => string ; } ; const TRANSFORMATIONS = { bytes32 : ethers . utils . formatBytes32String , } ; function buildSchemaHeader ( types ) { const allShortTypes = Object . keys ( PARAMETER_SHORT_TYPES ) ; const selectedShortTypes = types . reduce ( ( acc , type ) => { const shortType = allShortTypes . find ( ( st ) => PARAMETER_SHORT_TYPES [ st as ABIParameterTypeShort ] === type ) ; return [ ... acc , shortType ! ] ; } , [ ] ) ; return `1${ selectedShortTypes . join ( '' ) }` ; } function buildNameValuePairs ( parameters ) { return flatMap ( parameters , ( parameter ) => { const { name , value , type } = parameter ; const transform = TRANSFORMATIONS [ type ] ; const encodedName = ethers . utils . formatBytes32String ( name ! ) ; if ( ! transform ) { return [ encodedName , value ] ; } const encodedValue = transform ( value ) ; return [ encodedName , encodedValue ] ; } ) ; } export function encode ( parameters ) { const types = parameters . map ( ( parameter ) => parameter . type ) as ABIParameterType [ ] ; const nameTypePairs = flatMap ( types , ( type ) => [ 'bytes32' , type ] ) ; const allTypes = [ 'bytes32' , ... nameTypePairs ] ; const schemaHeader = buildSchemaHeader ( types as ABIParameterType [ ] ) ; const encodedHeader = ethers . utils . formatBytes32String ( schemaHeader ) ; const flatNameValues = buildNameValuePairs ( parameters ) ; const allValues = [ encodedHeader , ... flatNameValues ] ; const encoder = new ethers . utils . AbiCoder ( ) ; return encoder . encode ( allTypes , allValues ) ; }