lodash#mapValues TypeScript Examples

The following examples show how to use lodash#mapValues. 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: site.utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
excludeSpotterData = (
  data: SpotterData,
  exclusionDates: ExclusionDates[],
) => {
  if (exclusionDates.length === 0) {
    return data;
  }

  return mapValues(data, (metricData) =>
    filterMetricDataByDate(exclusionDates, metricData),
  );
}
Example #2
Source File: deployMainnet.ts    From optimism-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
async function main() {
  console.log('Deploying on mainnet')
  const l1Provider = new JsonRpcProvider(L1_MAINNET_RPC_URL)
  const l1Deployer = new hre.ethers.Wallet(L1_MAINNET_DEPLOYER_PRIV_KEY, l1Provider)

  const l2Provider = new JsonRpcProvider(L2_MAINNET_RPC_URL)
  const l2Deployer = new hre.ethers.Wallet(L2_MAINNET_DEPLOYER_PRIV_KEY, l2Provider)

  const deploymentInfo = await deploy({
    desiredL2DaiAddress: '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1',
    l1Deployer: l1Deployer,
    l2Deployer: l2Deployer,
    L1_DAI_ADDRESS: L1_MAINNET_DAI_ADDRESS,
    L1_PAUSE_PROXY_ADDRESS: L1_MAINNET_PAUSE_PROXY_ADDRESS,
    L1_ESM_ADDRESS: L1_MAINNET_ESM_ADDRESS,
    L1_XDOMAIN_MESSENGER: L1_MAINNET_XDOMAIN_MESSENGER,
    L2_XDOMAIN_MESSENGER: L2_MAINNET_XDOMAIN_MESSENGER,
    L1_TX_OPTS: {},
    L2_TX_OPTS: {},
  })

  const allContractInfo = {
    l1Dai: L1_MAINNET_DAI_ADDRESS,
    ...mapValues(deploymentInfo, (v) => v.address),
  }

  console.log(JSON.stringify(allContractInfo, null, 2))
}
Example #3
Source File: utils.ts    From aqualink-app with MIT License 6 votes vote down vote up
calculateSondeDataMeanValues = (
  metrics: SondeMetricsKeys[],
  timeSeriesData?: TimeSeriesData
) =>
  mapValues(pick(timeSeriesData, map(metrics, camelCase)), (data) =>
    meanBy(data?.sonde?.data, "value")
  )
Example #4
Source File: paramsSerializer.ts    From linkedin-private-api with MIT License 6 votes vote down vote up
paramsSerializer = (params: Record<string, string | Record<string, string>>): string => {
  const encodedParams = mapValues(params, value => {
    if (!isArray(value) && !isPlainObject(value)) {
      return value.toString();
    }

    if (isArray(value)) {
      return `List(${value.join(',')})`;
    }

    const encodedList = reduce(
      value as Record<string, string>,
      (res, filterVal, filterKey) => `${res}${res ? ',' : ''}${encodeFilter(filterVal, filterKey)}`,
      '',
    );

    return `List(${encodedList})`;
  });

  return stringify(encodedParams, undefined, undefined, {
    encodeURIComponent: uri => uri,
  });
}
Example #5
Source File: go-to.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
mapValues(pages, (v, k) => {
  goTo.pages[k] = `${goTo.pagePrefix}${k}`;
  goTo.pagePathMap[k] = v.match(/\{.+\}/) ? pathFormat(v) : v;
  goTo.resolve[k] = (params?: Obj, prependOrigin?: boolean) => {
    const orgName = get(location.pathname.split('/'), '[1]') || '-';
    const [urlParams, urlQuery] = routeInfoStore.getState((s) => [s.params, s.query]);
    const pathParams = { orgName, ...urlParams, ...urlQuery, ...params };
    const prefix = prependOrigin ? window.location.origin : '';
    const pagePath = pathFormat(v)(pathParams);
    return prefix + pagePath;
  };
});
Example #6
Source File: to-generated-auto-extractor.ts    From js-client with MIT License 6 votes vote down vote up
toGeneratedAutoExtractors = (raw: RawGeneratedAutoExtractors): GeneratedAutoExtractors =>
	mapValues(raw, extractors =>
		extractors.map(
			(ex): GeneratedAutoExtractor => ({
				confidence: ex.Confidence,
				entries: (ex.Entries ?? []).map(toSearchEntry),
				explorerEntries: (ex.Explore ?? []).map(toDataExplorerEntry),
				autoExtractor: toAutoExtractor(ex.Extractor),
			}),
		),
	)
Example #7
Source File: deployMainnet.ts    From arbitrum-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
async function main() {
  const pkey = getRequiredEnv('L1_MAINNET_DEPLOYER_PRIV_KEY')
  const l1Rpc = getRequiredEnv('L1_MAINNET_RPC_URL')
  const l2Rpc = getRequiredEnv('L2_MAINNET_RPC_URL')

  const network = await getMainnetNetworkConfig({ pkey, l1Rpc, l2Rpc })
  console.log(`Deploying to Mainnet using: ${network.l1.deployer.address}`)
  const routerDeployment = await getMainnetRouterDeployment(network)

  const l1BlockOfBeginningOfDeployment = await network.l1.provider.getBlockNumber()
  const l2BlockOfBeginningOfDeployment = await network.l2.provider.getBlockNumber()

  const bridgeDeployment = await deployBridge(network, routerDeployment, '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1')

  await performSanityChecks(
    network,
    bridgeDeployment,
    l1BlockOfBeginningOfDeployment,
    l2BlockOfBeginningOfDeployment,
    true,
  )

  console.log(
    JSON.stringify(
      mapValues(bridgeDeployment, (v) => v.address),
      null,
      2,
    ),
  )
}
Example #8
Source File: deployKovan.ts    From optimism-dai-bridge with GNU Affero General Public License v3.0 6 votes vote down vote up
async function main() {
  console.log('Deploying on kovan')
  const l1Provider = new JsonRpcProvider(L1_KOVAN_RPC_URL)
  const l1Deployer = new hre.ethers.Wallet(L1_KOVAN_DEPLOYER_PRIV_KEY, l1Provider)

  const l2Provider = new JsonRpcProvider(L2_KOVAN_RPC_URL)
  const l2Deployer = new hre.ethers.Wallet(L2_KOVAN_DEPLOYER_PRIV_KEY, l2Provider)

  const deploymentInfo = await deploy({
    desiredL2DaiAddress: '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1',
    l1Deployer: l1Deployer,
    l2Deployer: l2Deployer,
    L1_DAI_ADDRESS: L1_KOVAN_DAI_ADDRESS,
    L1_PAUSE_PROXY_ADDRESS: L1_KOVAN_PAUSE_PROXY_ADDRESS,
    L1_ESM_ADDRESS: L1_KOVAN_ESM_ADDRESS,
    L2_XDOMAIN_MESSENGER: L2_KOVAN_XDOMAIN_MESSENGER,
    L1_XDOMAIN_MESSENGER: L1_KOVAN_XDOMAIN_MESSENGER,
    L1_TX_OPTS: {
      gasPrice: 3000000000, // 3 gwei
    },
    L2_TX_OPTS: {},
  })

  const allContractInfo = {
    l1Dai: L1_KOVAN_DAI_ADDRESS,
    ...mapValues(deploymentInfo, (v) => v.address),
  }

  console.log(JSON.stringify(allContractInfo, null, 2))
}
Example #9
Source File: config.ts    From solana-program-registry with Apache License 2.0 6 votes vote down vote up
loadOrganizations = async (): Promise<
  Record<string, Organization>
> => {
  const orgsListRaw = await fs.readFile(`${__dirname}/../organizations.yml`);
  const orgsList = parse(orgsListRaw.toString()) as Record<
    string,
    Omit<Organization, "github">
  >;
  return mapValues(orgsList, (org, github) => ({ ...org, github }));
}
Example #10
Source File: action.ts    From querybook with Apache License 2.0 6 votes vote down vote up
export function normalizeRawDataDoc(rawDataDoc) {
    const normalizedData = normalize(rawDataDoc, dataDocSchema);
    const dataDoc = normalizedData.entities.dataDoc[normalizedData.result];
    const { dataDocCell: dataDocCellById = {} } = normalizedData.entities;
    const postProcessedCellById = mapValues(dataDocCellById, deserializeCell);

    return {
        dataDoc,
        dataDocCellById: postProcessedCellById,
    };
}
Example #11
Source File: index.tsx    From roam-toolkit with MIT License 6 votes vote down vote up
ReactHotkeys = ({keyMap, handlers}: Props) => {
    /**
     * Key sequences like 'g g' mess up the other shortcuts
     * See https://github.com/greena13/react-hotkeys/issues/229
     * And https://github.com/greena13/react-hotkeys/issues/219
     *
     * Workaround by separating sequences and single chords into different react components:
     * https://github.com/greena13/react-hotkeys/issues/219#issuecomment-540680435
     */
    const hotkeys: Dictionary<Hotkey> = mapValues(
        zipObjects(keyMap, handlers),
        ([keySequenceString, handler]): Hotkey => [KeySequence.fromString(keySequenceString), handler]
    )

    const singleChordHotkeys = pickBy(hotkeys, usesOneKeyChord)
    const multiChordHotkeys = pickBy(hotkeys, usesMultipleKeyChords)

    return (
        <>
            <GlobalHotKeysWithoutConflictingWithNativeHotkeys
                keyMap={mapValues(singleChordHotkeys, toKeySequence)}
                handlers={mapValues(singleChordHotkeys, toHandler)}
            />
            <GlobalHotKeysWithoutConflictingWithNativeHotkeys
                keyMap={mapValues(multiChordHotkeys, toKeySequence)}
                handlers={mapValues(multiChordHotkeys, toHandler)}
            />
        </>
    )
}
Example #12
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
/**
   * load workspaces in sync, and ensure it is an Object
   */
  getInitWorkspacesForCache = (): Record<string, IWorkspace> => {
    const workspacesFromDisk = settings.getSync(`workspaces`) ?? {};
    return typeof workspacesFromDisk === 'object' && !Array.isArray(workspacesFromDisk)
      ? mapValues(pickBy(workspacesFromDisk, (value) => value !== null) as unknown as Record<string, IWorkspace>, (workspace) =>
          this.sanitizeWorkspace(workspace),
        )
      : {};
  };
Example #13
Source File: snapshots.ts    From discord-bot with MIT License 6 votes vote down vote up
/**
 * Converts a snapshot object (from API) to an array of metric results
 */
export function toResults(snapshot: Snapshot, type?: MetricType): MetricResult[] {
  const results = Object.values(
    mapValues(snapshot, (val: any, key) => {
      return val ? { name: key, type: getType(key), ...val } : null;
    })
  ).filter(r => r && (!type || r.type === type));

  // If it's skill results, add the level field
  if (type === MetricType.Skill) {
    // Calculate the total level from the skill results
    const totalLevel = getTotalLevel(results);
    // Add the level field to each skill result
    results.forEach(r => (r.level = r.name === 'overall' ? totalLevel : getLevel(r.experience)));
  }

  return results;
}
Example #14
Source File: delta.service.ts    From wise-old-man with MIT License 6 votes vote down vote up
/**
 * Gets the all the player deltas (gains), for every period.
 */
async function getPlayerDeltas(playerId: number) {
  const latest = await snapshotService.findLatest(playerId);
  const player = await playerService.findById(playerId);

  const periodDeltas = await Promise.all(
    PERIODS.map(async period => {
      const deltas = await getPlayerPeriodDeltas(playerId, period, latest, player);
      return { period, deltas };
    })
  );

  // Turn an array of deltas, into an object, using the period as a key,
  // then include only the deltas array in the final object, not the period fields
  return mapValues(keyBy(periodDeltas, 'period'), p => p.deltas);
}
Example #15
Source File: util.ts    From S2 with MIT License 6 votes vote down vote up
getSwitcherState = (fields: SwitcherFields): SwitcherState =>
  mapValues(fields, 'items')
Example #16
Source File: utils.ts    From prism-frontend with MIT License 6 votes vote down vote up
convertToTableData = (result: ExposedPopulationResult) => {
  const {
    key,
    groupBy,
    statistic,
    featureCollection: { features },
  } = result;

  const fields = uniq(features.map(f => f.properties && f.properties[key]));

  const featureProperties = features.map(feature => {
    return {
      [groupBy]: feature.properties?.[groupBy],
      [key]: feature.properties?.[key],
      [statistic]: feature.properties?.[statistic],
    };
  });

  const rowData = mapValues(_groupBy(featureProperties, groupBy), k => {
    return mapValues(_groupBy(k, key), v =>
      parseInt(
        v.map(x => x[statistic]).reduce((acc, value) => acc + value),
        10,
      ),
    );
  });

  const groupedRowData = Object.keys(rowData).map(k => {
    return {
      [groupBy]: k,
      ...rowData[k],
    };
  });

  const groupedRowDataWithAllLabels = groupedRowData.map(row => {
    const labelsWithoutValue = difference(fields, keysIn(row));
    const extras = labelsWithoutValue.map(k => ({ [k]: 0 }));
    return extras.length !== 0 ? assign(row, ...extras) : row;
  });

  const headlessRows = groupedRowDataWithAllLabels.map(row => {
    // TODO - Switch between MAX and SUM depending on the polygon source.
    // Then re-add "Total" to the list of columns
    // const total = fields.map(f => row[f]).reduce((a, b) => a + b);
    // return assign(row, { Total: total });
    return row;
  });

  const columns = [groupBy, ...fields]; // 'Total'
  const headRow = zipObject(columns, columns);
  const rows = [headRow, ...headlessRows];
  return { columns, rows };
}
Example #17
Source File: selector.ts    From redux-with-domain with MIT License 6 votes vote down vote up
export function createSelectors(namespace, selectors, presenter, initialState) {
  const globalizeSelector = (selector, key) => (...params) => {
    const stateValue = _getStateValue(
      key,
      currentState,
      namespace,
      initialState
    )

    selectorLoopChecker.start(namespace, key)

    if (params[0] === currentState) {
      params.shift()
    }

    const res = presenter.loaded
      ? selector(stateValue, presenter.selectors, ...params)
      : selector(stateValue, null, ...params)

    selectorLoopChecker.end(namespace, key)

    return res
  }

  return mapValues(selectors, globalizeSelector)
}
Example #18
Source File: fieldFormatter.ts    From generator-earth with MIT License 6 votes vote down vote up
/**
 * format对象中所有moment值
 */
export function mapMoment(obj, f='YYYY-MM-DD') {
    if (!obj)
        return null
    
    return mapValues(obj, function(v) {
        return moment.isMoment(v) ? v.format(f) : v
    })
}
Example #19
Source File: index.ts    From openzeppelin-transpiler with MIT License 6 votes vote down vote up
function getExtraOutputPaths(
  paths: Paths,
  options?: TranspileOptions,
): Record<'initializable' | 'withInit', string> {
  const outputPaths = mapValues(
    {
      initializable: 'Initializable.sol',
      withInit: 'mocks/WithInit.sol',
    },
    s => path.relative(paths.root, path.join(paths.sources, s)),
  );

  if (options?.initializablePath) {
    outputPaths.initializable = options?.initializablePath;
  }

  return outputPaths;
}
Example #20
Source File: selector.ts    From redux-with-domain with MIT License 6 votes vote down vote up
function _transformSelectors(namespace, selectors, initialState) {
  const globalizeSelector = (selector, key) => (...params) => {
    if (isArray(params) && params.length > 1 && params[0] === currentState) {
      params.shift()
    }
    const stateValue = _getStateValue(
      key,
      currentState,
      namespace,
      initialState
    )

    const res = selector(stateValue, {
      payload: params.length === 1 ? params[0] : params
    })

    return res
  }

  return mapValues(selectors, globalizeSelector)
}
Example #21
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 5 votes vote down vote up
private getWorkspacesWithMetadata(): Record<string, IWorkspaceWithMetadata> {
    return mapValues(this.getWorkspacesSync(), (workspace: IWorkspace, id): IWorkspaceWithMetadata => ({ ...workspace, metadata: this.getMetaDataSync(id) }));
  }
Example #22
Source File: warp-http-client.ts    From openapi-generator-typescript with MIT License 5 votes vote down vote up
warpHttpClient = <OpenApiOperationsDictionary>(
  openApiDocs: any
) => <uri extends OpenApiRequestRegistryURIS>(
  httpClient: (
    requestParams: {
      readonly docNamespace: keyof OpenApiOperationsDictionary;
      readonly operationId: Any.Keys<
        OpenApiOperationsDictionary[keyof OpenApiOperationsDictionary]
      >;
      readonly getUrl: (params: any) => string;
      readonly method: string;
      readonly params: any;
      readonly parameterNames: {
        readonly path: ReadonlyArray<string>;
        readonly query: ReadonlyArray<string>;
        readonly header: ReadonlyArray<string>;
        readonly cookie: ReadonlyArray<string>;
      };
    },
    body: any,
    options: any
  ) => any
) =>
  (mapValues(openApiDocs, ({ operations }, docNamespace: any) =>
    mapValues(
      operations,
      ({ getUrl, method, parameterNames }: any, operationId: any) => (
        params: any,
        body: any,
        options: any
      ) =>
        httpClient(
          {
            docNamespace,
            operationId,
            getUrl,
            method,
            parameterNames,
            params,
          },
          body,
          options
        )
    )
  ) as any) as {
    [namespace in keyof OpenApiOperationsDictionary]: {
      [operationId in keyof OpenApiOperationsDictionary[namespace]]: OpenApiRequest<
        uri,
        Any.At<
          {} & OpenApiOperationsDictionary[namespace][operationId],
          'Parameter'
        >,
        Object.UnionOf<
          {} & Object.UnionOf<
            {} & Any.At<
              {} & OpenApiOperationsDictionary[namespace][operationId],
              'Response'
            >
          >
        >,
        Object.UnionOf<
          {} & Any.At<
            {} & OpenApiOperationsDictionary[namespace][operationId],
            'RequestBody'
          >
        >,
        Any.At<
          {} & OpenApiOperationsDictionary[namespace][operationId],
          'requestBody'
        >
      >;
    };
  }
Example #23
Source File: transform.ts    From openzeppelin-transpiler with MIT License 5 votes vote down vote up
results(): { [file in string]: string } {
    return mapValues(this.state, s => s.content.toString());
  }
Example #24
Source File: f2p.ts    From wise-old-man with MIT License 5 votes vote down vote up
calculateTTM(experiences: Experiences): number {
    const cappedExp = mapValues(experiences, val => Math.min(val, 13_034_431));
    return this.maxedEHP - this.calculateEHP(cappedExp);
  }
Example #25
Source File: sensors.service.ts    From aqualink-app with MIT License 5 votes vote down vote up
private async getClosestTimeSeriesData(
    diveDate: Date,
    siteId: number,
    metrics: Metric[],
    sourceTypes: SourceType[],
    surveyPointId?: number,
  ) {
    const surveyPointCondition = surveyPointId
      ? `source.survey_point_id = ${surveyPointId}`
      : 'source.survey_point_id IS NULL';
    // We will use this many times in our query, so we declare it as constant
    const diff = `(time_series.timestamp::timestamp - '${diveDate.toISOString()}'::timestamp)`;

    // First get all sources needed to avoid inner join later
    const sources = await this.sourcesRepository
      .createQueryBuilder('source')
      .where('source.type IN (:...sourceTypes)', { sourceTypes })
      .andWhere('source.site_id = :siteId', { siteId })
      .andWhere(surveyPointCondition)
      .getMany();

    if (!sources.length) {
      return {};
    }

    // Create map from source_id to source entity
    const sourceMap = keyBy(sources, (source) => source.id);

    // Grab all data at an interval of +/- 24 hours around the diveDate
    // Order (descending) those data by the absolute time distance between the data and the survey diveDate
    // This way the closest data point for each metric for each source type will be the last row
    const timeSeriesData: TimeSeriesData[] = await this.timeSeriesRepository
      .createQueryBuilder('time_series')
      .select('time_series.timestamp', 'timestamp')
      .addSelect('time_series.value', 'value')
      .addSelect('time_series.metric', 'metric')
      .addSelect('time_series.source_id', 'source')
      .where(`${diff} < INTERVAL '1 d'`)
      .andWhere(`${diff} > INTERVAL '-1 d'`)
      .andWhere('time_series.metric IN (:...metrics)', { metrics })
      .andWhere('time_series.source_id IN (:...sourceIds)', {
        sourceIds: Object.keys(sourceMap),
      })
      .orderBy(
        `time_series.source_id, metric, (CASE WHEN ${diff} < INTERVAL '0' THEN (-${diff}) ELSE ${diff} END)`,
        'DESC',
      )
      .getRawMany();

    // Group the data by source id
    const groupedData = groupBy(timeSeriesData, (o) => o.source);

    return Object.keys(groupedData).reduce<SensorDataDto>((data, key) => {
      return {
        ...data,
        // Replace source id by source using the mapped source object
        // Keep only timestamps and value from the resulting objects
        [sourceMap[key].type]: mapValues(
          // Use key by to group the data by metric and keep only the last entry, i.e. the closest one
          keyBy(groupedData[key], (grouped) => grouped.metric),
          (v) => ({ timestamp: v.timestamp, value: v.value }),
        ),
      };
    }, {});
  }
Example #26
Source File: settings.state.ts    From nextclade with MIT License 5 votes vote down vote up
resultsTableColumnWidthsPxAtom = selector<Record<keyof typeof COLUMN_WIDTHS, string>>({
  key: 'columnWidthsPx',
  get: ({ get }) => mapValues(get(resultsTableColumnWidthsAtom), (width) => `${width}px`),
})
Example #27
Source File: bridge.test.ts    From arbitrum-dai-bridge with GNU Affero General Public License v3.0 5 votes vote down vote up
export async function setupTest() {
  const pkey = getRequiredEnv('E2E_TESTS_PKEY')
  const l1Rpc = getRequiredEnv('E2E_TESTS_L1_RPC')
  const l2Rpc = getRequiredEnv('E2E_TESTS_L2_RPC')
  const network = await getRinkebyNetworkConfig({ pkey, l1Rpc, l2Rpc })

  let bridgeDeployment: BridgeDeployment
  let routerDeployment: RouterDeployment

  // this is a mechanism to reuse old deployment -- speeds up development
  const staticDeploymentString = getOptionalEnv('E2E_TESTS_DEPLOYMENT')
  if (staticDeploymentString) {
    console.log('Using static deployment...')
    const deployment = JSON.parse(staticDeploymentString)
    routerDeployment = await useStaticRouterDeployment(network, deployment)
    bridgeDeployment = await useStaticDeployment(network, deployment)
  } else {
    routerDeployment = await deployRouter(network)
    bridgeDeployment = await deployBridge(network, routerDeployment)

    await setGatewayForToken({
      l1Router: routerDeployment.l1GatewayRouter,
      l2Router: routerDeployment.l2GatewayRouter,
      l2Provider: network.l2.provider,
      tokenGateway: bridgeDeployment.l1DaiGateway,
    })
  }

  console.log(
    'Bridge deployment: ',
    JSON.stringify(
      mapValues(bridgeDeployment, (v) => v.address),
      null,
      2,
    ),
  )

  console.log(
    'Router deployment: ',
    JSON.stringify(
      mapValues(routerDeployment, (v) => v.address),
      null,
      2,
    ),
  )

  return {
    bridgeDeployment,
    routerDeployment,
    network,
  }
}
Example #28
Source File: buildTVLList.ts    From rewarder-list with GNU Affero General Public License v3.0 5 votes vote down vote up
buildTVLList = async (network: Network): Promise<void> => {
  const dir = `${__dirname}/../../data/${network}/`;
  await fs.mkdir(dir, { recursive: true });

  const rewarderMetas = JSON.parse(
    (await fs.readFile(`${dir}/all-rewarders.json`)).toString()
  ) as Record<string, RewarderMeta>;

  const quarriesByStakedMint = mapValues(
    groupBy(
      Object.values(rewarderMetas).flatMap((rew) =>
        rew.quarries.map((q) => ({
          address: q.stakedToken.mint,
          quarry: q.quarry,
        }))
      ),
      (q) => q.address
    ),
    (v) => v.map((q) => q.quarry)
  );

  const tokenList = JSON.parse(
    (await fs.readFile(`${dir}/token-list.json`)).toString()
  ) as TokenList;

  const coingeckoIDs = Object.keys(quarriesByStakedMint).reduce(
    (acc: Record<string, string>, mint) => {
      const id = tokenList.tokens.find((t) => t.address === mint)?.extensions
        ?.coingeckoId;
      if (id) {
        acc[mint] = id;
      }
      return acc;
    },
    {}
  );

  const tvl = { quarriesByStakedMint, coingeckoIDs };

  await fs.writeFile(`${dir}/tvl.json`, stringify(tvl));
}
Example #29
Source File: loadConfig.ts    From tribeca-registry with Apache License 2.0 5 votes vote down vote up
loadTrackedAccountInfo = (
  infos: Record<string, TrackedAccountInfoJSON>
): Record<string, TrackedAccountInfo> => {
  return mapValues(infos, ({ address, ...info }) => ({
    ...info,
    address: new PublicKey(address),
  }));
}