immutable#Set TypeScript Examples

The following examples show how to use immutable#Set. 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: safe.ts    From multisig-react with MIT License 6 votes vote down vote up
makeSafe = Record<SafeRecordProps>({
  name: '',
  address: '',
  threshold: 0,
  ethBalance: '0',
  owners: List([]),
  modules: [],
  spendingLimits: [],
  activeTokens: Set(),
  activeAssets: Set(),
  blacklistedTokens: Set(),
  blacklistedAssets: Set(),
  balances: Map(),
  nonce: 0,
  latestIncomingTxBlock: 0,
  recurringUser: undefined,
  currentVersion: '',
  needsUpdate: false,
  featuresEnabled: [],
})
Example #2
Source File: safe.ts    From multisig-react with MIT License 6 votes vote down vote up
buildSafe = (storedSafe: SafeRecordProps): SafeRecordProps => {
  const names = storedSafe.owners.map((owner) => owner.name)
  const addresses = storedSafe.owners.map((owner) => checksumAddress(owner.address))
  const owners = buildOwnersFrom(Array.from(names), Array.from(addresses))
  const activeTokens = Set(storedSafe.activeTokens)
  const activeAssets = Set(storedSafe.activeAssets)
  const blacklistedTokens = Set(storedSafe.blacklistedTokens)
  const blacklistedAssets = Set(storedSafe.blacklistedAssets)
  const balances = Map(storedSafe.balances)

  return {
    ...storedSafe,
    owners,
    balances,
    activeTokens,
    blacklistedTokens,
    activeAssets,
    blacklistedAssets,
    latestIncomingTxBlock: 0,
    modules: null,
  }
}
Example #3
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
safeActiveTokensSelector = createSelector(
  safeSelector,
  (safe): Set<string> => {
    if (!safe) {
      return Set()
    }

    return safe.activeTokens
  },
)
Example #4
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
safeActiveAssetsSelector = createSelector(
  safeSelector,
  (safe): Set<string> => {
    if (!safe) {
      return Set()
    }
    return safe.activeAssets
  },
)
Example #5
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
safeBlacklistedTokensSelector = createSelector(
  safeSelector,
  (safe): Set<string> => {
    if (!safe) {
      return Set()
    }

    return safe.blacklistedTokens
  },
)
Example #6
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
safeBlacklistedAssetsSelector = createSelector(
  safeSelector,
  (safe): Set<string> => {
    if (!safe) {
      return Set()
    }

    return safe.blacklistedAssets
  },
)
Example #7
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
getBlacklistedTokensAddressesForAllSafes = createSelector(safesListSelector, (safes) => {
  const addresses = Set().withMutations((set) => {
    safes.forEach((safe) => {
      safe.blacklistedTokens.forEach((tokenAddress) => {
        set.add(tokenAddress)
      })
    })
  })

  return addresses
})
Example #8
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
getActiveTokensAddressesForAllSafes = createSelector(safesListSelector, (safes) => {
  const addresses = Set().withMutations((set) => {
    safes.forEach((safe) => {
      safe.activeTokens.forEach((tokenAddress) => {
        set.add(tokenAddress)
      })
    })
  })

  return addresses
})
Example #9
Source File: index.ts    From multisig-react with MIT License 5 votes vote down vote up
safeActiveAssetsSelectorBySafe = (safeAddress: string, safes: SafesMap): Set<string> =>
  safes.get(safeAddress)?.get('activeAssets') || Set()
Example #10
Source File: key-chord.ts    From roam-toolkit with MIT License 5 votes vote down vote up
private readonly modifiers: Set<Modifier>
Example #11
Source File: key-chord.ts    From roam-toolkit with MIT License 5 votes vote down vote up
constructor(key: string, modifiers: Set<Modifier>) {
        this.key = key
        this.modifiers = modifiers
    }
Example #12
Source File: key-chord.ts    From roam-toolkit with MIT License 5 votes vote down vote up
static fromString(keyChordString: KeyChordString): KeyChord {
        const keys = keyChordString.split('+')
        return new KeyChord(keys.pop()!, Set(keys.map(modifier => modifier.toLowerCase() as Modifier)))
    }
Example #13
Source File: shouldSafeStoreBeUpdated.test.ts    From multisig-react with MIT License 5 votes vote down vote up
getMockedOldSafe = ({
  address,
  needsUpdate,
  balances,
  recurringUser,
  blacklistedAssets,
  blacklistedTokens,
  activeAssets,
  activeTokens,
  owners,
  featuresEnabled,
  currentVersion,
  latestIncomingTxBlock,
  ethBalance,
  threshold,
  name,
  nonce,
  modules,
  spendingLimits,
}: Partial<SafeRecordProps>): SafeRecordProps => {
  const owner1 = {
    name: 'MockedOwner1',
    address: '0x3bE3c2dE077FBC409ae50AFFA66a94a9aE669A8d',
  }
  const owner2 = {
    name: 'MockedOwner2',
    address: '0xA2366b0c2607de70777d87aCdD1D22F0708fA6a3',
  }
  const mockedActiveTokenAddress1 = '0x36591cd3DA96b21Ac9ca54cFaf80fe45107294F1'
  const mockedActiveTokenAddress2 = '0x92aF97cbF10742dD2527ffaBA70e34C03CFFC2c1'
  const mockedActiveAssetsAddress1 = '0x503ab2a6A70c6C6ec8b25a4C87C784e1c8f8e8CD'
  const mockedActiveAssetsAddress2 = '0xfdd4E685361CB7E89a4D27e03DCd0001448d731F'
  const mockedBlacklistedTokenAddress1 = '0xc7d892dca37a244Fb1A7461e6141e58Ead460282'
  const mockedBlacklistedAssetAddress1 = '0x0ac539137c4c99001f16Dd132E282F99A02Ddc3F'

  return {
    name: name || 'MockedSafe',
    address: address || '0xAE173F30ec9A293d37c44BA68d3fCD35F989Ce9F',
    threshold: threshold || 2,
    ethBalance: ethBalance || '10',
    owners: owners || List([owner1, owner2]),
    modules: modules || [],
    spendingLimits: spendingLimits || [],
    activeTokens: activeTokens || Set([mockedActiveTokenAddress1, mockedActiveTokenAddress2]),
    activeAssets: activeAssets || Set([mockedActiveAssetsAddress1, mockedActiveAssetsAddress2]),
    blacklistedTokens: blacklistedTokens || Set([mockedBlacklistedTokenAddress1]),
    blacklistedAssets: blacklistedAssets || Set([mockedBlacklistedAssetAddress1]),
    balances:
      balances ||
      Map({
        [mockedActiveTokenAddress1]: '100',
        [mockedActiveTokenAddress2]: '10',
      }),
    nonce: nonce || 2,
    latestIncomingTxBlock: latestIncomingTxBlock || 1,
    recurringUser: recurringUser || false,
    currentVersion: currentVersion || 'v1.1.1',
    needsUpdate: needsUpdate || false,
    featuresEnabled: featuresEnabled || [],
  }
}
Example #14
Source File: safe.balances.test.ts    From multisig-react with MIT License 5 votes vote down vote up
describe('Feature > Balances', () => {
  let store
  const safeAddress = '0xdfA693da0D16F5E7E78FdCBeDe8FC6eBEa44f1Cf'
  beforeEach(async () => {
    store = aNewStore()
  })

  it('It should return an updated balance when updates active tokens', async () => {
    // given
    const tokensAmount = '100'
    const token = makeToken({
      address: '0x00Df91984582e6e96288307E9c2f20b38C8FeCE9',
      name: 'OmiseGo',
      symbol: 'OMG',
      decimals: 18,
      logoUri:
        'https://github.com/TrustWallet/tokens/blob/master/images/0x6810e776880c02933d47db1b9fc05908e5386b96.png?raw=true',
    })
    const balances = Map({
      [token.address]: tokensAmount,
    })
    const expectedResult = '100'

    // when
    store.dispatch(updateSafe({ address: safeAddress, balances }))
    store.dispatch(updateActiveTokens(safeAddress, Set([token.address])))

    const safe = safesMapSelector(store.getState()).get(safeAddress)
    const balanceResult = safe?.get('balances').get(token.address)
    const activeTokens = safe?.get('activeTokens')
    const tokenIsActive = activeTokens?.has(token.address)

    // then
    expect(balanceResult).toBe(expectedResult)
    expect(tokenIsActive).toBe(true)
  })

  it('The store should have an updated ether balance after updating the value', async () => {
    // given
    const etherAmount = '1'
    const expectedResult = '1'

    // when
    store.dispatch(updateSafe({ address: safeAddress, ethBalance: etherAmount }))
    const safe = safesMapSelector(store.getState()).get(safeAddress)
    const balanceResult = safe?.get('ethBalance')

    // then
    expect(balanceResult).toBe(expectedResult)
  })
})
Example #15
Source File: index.ts    From multisig-react with MIT License 5 votes vote down vote up
safeBlacklistedAssetsSelectorBySafe = (safeAddress: string, safes: SafesMap): Set<string> =>
  safes.get(safeAddress)?.get('blacklistedAssets') || Set()
Example #16
Source File: fetchSafe.ts    From multisig-react with MIT License 5 votes vote down vote up
buildSafe = async (
  safeAdd: string,
  safeName: string,
  latestMasterContractVersion?: string,
): Promise<SafeRecordProps> => {
  const safeAddress = checksumAddress(safeAdd)

  const safeParams = ['getThreshold', 'nonce', 'VERSION', 'getOwners']
  const [
    [, thresholdStr, nonceStr, currentVersion, remoteOwners = []],
    safeInfo,
    localSafe,
    ethBalance,
  ] = await Promise.all([
    generateBatchRequests<[undefined, string | undefined, string | undefined, string | undefined, string[]]>({
      abi: GnosisSafeSol.abi as AbiItem[],
      address: safeAddress,
      methods: safeParams,
    }),
    getSafeInfo(safeAddress),
    getLocalSafe(safeAddress),
    getBalanceInEtherOf(safeAddress),
  ])

  const threshold = Number(thresholdStr)
  const nonce = Number(nonceStr)
  const owners = buildOwnersFrom(remoteOwners, localSafe)
  const needsUpdate = safeNeedsUpdate(currentVersion, latestMasterContractVersion)
  const featuresEnabled = enabledFeatures(currentVersion)
  const modules = await getModules(safeInfo)
  const spendingLimits = safeInfo ? await getSpendingLimits(safeInfo.modules, safeAddress) : null

  return {
    address: safeAddress,
    name: safeName,
    threshold,
    owners,
    ethBalance,
    nonce,
    currentVersion: currentVersion ?? '',
    needsUpdate,
    featuresEnabled,
    balances: localSafe?.balances || Map(),
    latestIncomingTxBlock: 0,
    activeAssets: Set(),
    activeTokens: Set(),
    blacklistedAssets: Set(),
    blacklistedTokens: Set(),
    modules,
    spendingLimits,
  }
}
Example #17
Source File: index.ts    From multisig-react with MIT License 5 votes vote down vote up
safeActiveAssetsListSelector = createSelector(safeActiveAssetsSelector, (safeList) => {
  if (!safeList) {
    return Set([])
  }
  return Set(safeList)
})
Example #18
Source File: updateBlacklistedTokens.ts    From multisig-react with MIT License 5 votes vote down vote up
updateBlacklistedTokens = (safeAddress: string, blacklistedTokens: Set<string>) => (dispatch: Dispatch): void => {
  dispatch(updateTokensList({ safeAddress, blacklistedTokens }))
}
Example #19
Source File: updateBlacklistedAssets.ts    From multisig-react with MIT License 5 votes vote down vote up
updateBlacklistedAssets = (safeAddress: string, blacklistedAssets: Set<string>) => (dispatch: Dispatch): void => {
  dispatch(updateAssetsList({ safeAddress, blacklistedAssets }))
}
Example #20
Source File: updateActiveTokens.ts    From multisig-react with MIT License 5 votes vote down vote up
updateActiveTokens = (safeAddress: string, activeTokens: Set<string>) => (dispatch: Dispatch): void => {
  dispatch(updateTokensList({ safeAddress, activeTokens }))
}
Example #21
Source File: updateActiveAssets.ts    From multisig-react with MIT License 5 votes vote down vote up
updateActiveAssets = (safeAddress: string, activeAssets: Set<string>) => (dispatch: Dispatch): void => {
  dispatch(updateAssetsList({ safeAddress, activeAssets }))
}
Example #22
Source File: shouldSafeStoreBeUpdated.test.ts    From multisig-react with MIT License 4 votes vote down vote up
describe('shouldSafeStoreBeUpdated', () => {
  it(`Given two equal safes, should return false`, () => {
    // given
    const oldSafe = getMockedOldSafe({})

    // When
    const expectedResult = shouldSafeStoreBeUpdated(oldSafe, oldSafe)

    // Then
    expect(expectedResult).toEqual(false)
  })
  it(`Given an old safe and a new address for the safe, should return true`, () => {
    // given
    const oldAddress = '0x123'
    const newAddress = '0x'
    const oldSafe = getMockedOldSafe({ address: oldAddress })
    const newSafeProps: Partial<SafeRecordProps> = {
      address: newAddress,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old safe and a new name for the safe, should return true`, () => {
    // given
    const oldName = 'oldName'
    const newName = 'newName'
    const oldSafe = getMockedOldSafe({ name: oldName })
    const newSafeProps: Partial<SafeRecordProps> = {
      name: newName,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old safe and a new threshold for the safe, should return true`, () => {
    // given
    const oldThreshold = 1
    const newThreshold = 2
    const oldSafe = getMockedOldSafe({ threshold: oldThreshold })
    const newSafeProps: Partial<SafeRecordProps> = {
      threshold: newThreshold,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old ethBalance and a new ethBalance for the safe, should return true`, () => {
    // given
    const oldEthBalance = '1'
    const newEthBalance = '2'
    const oldSafe = getMockedOldSafe({ ethBalance: oldEthBalance })
    const newSafeProps: Partial<SafeRecordProps> = {
      ethBalance: newEthBalance,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old owners list and a new owners list for the safe, should return true`, () => {
    // given
    const owner1 = {
      name: 'MockedOwner1',
      address: '0x3bE3c2dE077FBC409ae50AFFA66a94a9aE669A8d',
    }
    const owner2 = {
      name: 'MockedOwner2',
      address: '0xA2366b0c2607de70777d87aCdD1D22F0708fA6a3',
    }
    const oldSafe = getMockedOldSafe({ owners: List([owner1, owner2]) })
    const newSafeProps: Partial<SafeRecordProps> = {
      owners: List([owner1]),
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old modules list and a new modules list for the safe, should return true`, () => {
    // given
    const oldModulesList = []
    const newModulesList = null
    const oldSafe = getMockedOldSafe({ modules: oldModulesList })
    const newSafeProps: Partial<SafeRecordProps> = {
      modules: newModulesList,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old spendingLimits list and a new spendingLimits list for the safe, should return true`, () => {
    // given
    const oldSpendingLimitsList = []
    const newSpendingLimitsList = null
    const oldSafe = getMockedOldSafe({ spendingLimits: oldSpendingLimitsList })
    const newSafeProps: Partial<SafeRecordProps> = {
      modules: newSpendingLimitsList,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old activeTokens list and a new activeTokens list for the safe, should return true`, () => {
    // given
    const mockedActiveTokenAddress1 = '0x36591cd3DA96b21Ac9ca54cFaf80fe45107294F1'
    const mockedActiveTokenAddress2 = '0x92aF97cbF10742dD2527ffaBA70e34C03CFFC2c1'
    const oldActiveTokens = Set([mockedActiveTokenAddress1, mockedActiveTokenAddress2])
    const newActiveTokens = Set([mockedActiveTokenAddress1])
    const oldSafe = getMockedOldSafe({ activeTokens: oldActiveTokens })
    const newSafeProps: Partial<SafeRecordProps> = {
      activeTokens: newActiveTokens,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old activeAssets list and a new activeAssets list for the safe, should return true`, () => {
    // given
    const mockedActiveTokenAddress1 = '0x36591cd3DA96b21Ac9ca54cFaf80fe45107294F1'
    const mockedActiveTokenAddress2 = '0x92aF97cbF10742dD2527ffaBA70e34C03CFFC2c1'
    const oldActiveAssets = Set([mockedActiveTokenAddress1, mockedActiveTokenAddress2])
    const newActiveAssets = Set([mockedActiveTokenAddress1])
    const oldSafe = getMockedOldSafe({ activeAssets: oldActiveAssets })
    const newSafeProps: Partial<SafeRecordProps> = {
      activeAssets: newActiveAssets,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old blacklistedTokens list and a new blacklistedTokens list for the safe, should return true`, () => {
    // given
    const mockedActiveTokenAddress1 = '0x36591cd3DA96b21Ac9ca54cFaf80fe45107294F1'
    const mockedActiveTokenAddress2 = '0x92aF97cbF10742dD2527ffaBA70e34C03CFFC2c1'
    const oldBlacklistedTokens = Set([mockedActiveTokenAddress1, mockedActiveTokenAddress2])
    const newBlacklistedTokens = Set([mockedActiveTokenAddress1])
    const oldSafe = getMockedOldSafe({ blacklistedTokens: oldBlacklistedTokens })
    const newSafeProps: Partial<SafeRecordProps> = {
      blacklistedTokens: newBlacklistedTokens,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old blacklistedAssets list and a new blacklistedAssets list for the safe, should return true`, () => {
    // given
    const mockedActiveTokenAddress1 = '0x36591cd3DA96b21Ac9ca54cFaf80fe45107294F1'
    const mockedActiveTokenAddress2 = '0x92aF97cbF10742dD2527ffaBA70e34C03CFFC2c1'
    const oldBlacklistedAssets = Set([mockedActiveTokenAddress1, mockedActiveTokenAddress2])
    const newBlacklistedAssets = Set([mockedActiveTokenAddress1])
    const oldSafe = getMockedOldSafe({ blacklistedAssets: oldBlacklistedAssets })
    const newSafeProps: Partial<SafeRecordProps> = {
      blacklistedAssets: newBlacklistedAssets,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old balances list and a new balances list for the safe, should return true`, () => {
    // given
    const mockedActiveTokenAddress1 = '0x36591cd3DA96b21Ac9ca54cFaf80fe45107294F1'
    const mockedActiveTokenAddress2 = '0x92aF97cbF10742dD2527ffaBA70e34C03CFFC2c1'
    const oldBalances = Map({
      [mockedActiveTokenAddress1]: '100',
      [mockedActiveTokenAddress2]: '10',
    })
    const newBalances = Map({
      [mockedActiveTokenAddress1]: '100',
    })
    const oldSafe = getMockedOldSafe({ balances: oldBalances })
    const newSafeProps: Partial<SafeRecordProps> = {
      balances: newBalances,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old nonce and a new nonce for the safe, should return true`, () => {
    // given
    const oldNonce = 1
    const newNonce = 2
    const oldSafe = getMockedOldSafe({ nonce: oldNonce })
    const newSafeProps: Partial<SafeRecordProps> = {
      nonce: newNonce,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old newLatestIncomingTxBlock and a new newLatestIncomingTxBlock for the safe, should return true`, () => {
    // given
    const oldLatestIncomingTxBlock = 1
    const newLatestIncomingTxBlock = 2
    const oldSafe = getMockedOldSafe({ latestIncomingTxBlock: oldLatestIncomingTxBlock })
    const newSafeProps: Partial<SafeRecordProps> = {
      latestIncomingTxBlock: newLatestIncomingTxBlock,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old recurringUser and a new recurringUser for the safe, should return true`, () => {
    // given
    const oldRecurringUser = true
    const newRecurringUser = false
    const oldSafe = getMockedOldSafe({ recurringUser: oldRecurringUser })
    const newSafeProps: Partial<SafeRecordProps> = {
      recurringUser: newRecurringUser,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old recurringUser and a new recurringUser for the safe, should return true`, () => {
    // given
    const oldCurrentVersion = '1.1.1'
    const newCurrentVersion = '1.0.0'
    const oldSafe = getMockedOldSafe({ currentVersion: oldCurrentVersion })
    const newSafeProps: Partial<SafeRecordProps> = {
      currentVersion: newCurrentVersion,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old needsUpdate and a new needsUpdate for the safe, should return true`, () => {
    // given
    const oldNeedsUpdate = false
    const newNeedsUpdate = true
    const oldSafe = getMockedOldSafe({ needsUpdate: oldNeedsUpdate })
    const newSafeProps: Partial<SafeRecordProps> = {
      needsUpdate: newNeedsUpdate,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
  it(`Given an old featuresEnabled and a new featuresEnabled for the safe, should return true`, () => {
    // given
    const oldFeaturesEnabled = []
    const newFeaturesEnabled = undefined
    const oldSafe = getMockedOldSafe({ featuresEnabled: oldFeaturesEnabled })
    const newSafeProps: Partial<SafeRecordProps> = {
      featuresEnabled: newFeaturesEnabled,
    }

    // When
    const expectedResult = shouldSafeStoreBeUpdated(newSafeProps, oldSafe)

    // Then
    expect(expectedResult).toEqual(true)
  })
})
Example #23
Source File: index.tsx    From multisig-react with MIT License 4 votes vote down vote up
AddCustomToken = (props: Props): React.ReactElement => {
  const { activeTokens, onClose, parentList, safeAddress, setActiveScreen, tokens } = props
  const [formValues, setFormValues] = useState(INITIAL_FORM_STATE)
  const classes = useStyles()
  const dispatch = useDispatch()

  const handleSubmit = (values) => {
    const address = checksumAddress(values.address)
    const token = {
      address,
      decimals: values.decimals,
      symbol: values.symbol,
      name: values.symbol,
    }

    dispatch(addToken(token))
    if (values.showForAllSafes) {
      dispatch(activateTokenForAllSafes(token.address))
    } else {
      const activeTokensAddresses = Set(activeTokens.map(({ address }) => address))
      dispatch(updateActiveTokens(safeAddress, activeTokensAddresses.add(token.address)))
    }

    onClose()
  }

  const populateFormValuesFromAddress = async (tokenAddress) => {
    const tokenData = await getSymbolAndDecimalsFromContract(tokenAddress)

    if (tokenData.length) {
      const [symbol, decimals] = tokenData

      setFormValues({
        address: tokenAddress,
        symbol,
        decimals,
        name: symbol,
      } as any)
    }
  }

  const formSpyOnChangeHandler = async (state) => {
    const { dirty, errors, submitSucceeded, validating, values } = state
    // for some reason this is called after submitting, we don't need to update the values
    // after submit
    if (submitSucceeded) {
      return
    }

    if (dirty && !validating && errors.address) {
      setFormValues(INITIAL_FORM_STATE)
    }

    if (!errors.address && !validating && dirty) {
      await populateFormValuesFromAddress(values.address)
    }
  }

  const formMutators = {
    setTokenAddress: (args, state, utils) => {
      utils.changeValue(state, 'address', () => args[0])
    },
  }

  const goBack = () => {
    setActiveScreen(parentList)
  }

  return (
    <>
      <GnoForm
        initialValues={formValues}
        onSubmit={handleSubmit}
        formMutators={formMutators}
        testId={ADD_CUSTOM_TOKEN_FORM}
      >
        {(...args) => {
          const mutators = args[3]

          return (
            <>
              <Block className={classes.formContainer}>
                <Paragraph className={classes.title} noMargin size="lg" weight="bolder">
                  Add custom token
                </Paragraph>
                <AddressInput
                  fieldMutator={mutators.setTokenAddress}
                  className={classes.addressInput}
                  name="address"
                  placeholder="Token contract address*"
                  testId={ADD_CUSTOM_TOKEN_ADDRESS_INPUT_TEST_ID}
                  text="Token contract address*"
                  validators={[doesntExistInTokenList(tokens), addressIsTokenContract]}
                />
                <FormSpy
                  onChange={formSpyOnChangeHandler}
                  subscription={{
                    values: true,
                    errors: true,
                    validating: true,
                    dirty: true,
                    submitSucceeded: true,
                  }}
                />
                <Row>
                  <Col layout="column" xs={6}>
                    <Field
                      className={classes.addressInput}
                      component={TextField}
                      name="symbol"
                      placeholder="Token symbol*"
                      testId={ADD_CUSTOM_TOKEN_SYMBOLS_INPUT_TEST_ID}
                      text="Token symbol"
                      type="text"
                      validate={composeValidators(required, minMaxLength(2, 12))}
                    />
                    <Field
                      className={classes.addressInput}
                      component={TextField}
                      disabled
                      name="decimals"
                      placeholder="Token decimals*"
                      testId={ADD_CUSTOM_TOKEN_DECIMALS_INPUT_TEST_ID}
                      text="Token decimals*"
                      type="text"
                    />
                    <Block justify="center">
                      <Field
                        className={classes.checkbox}
                        component={Checkbox}
                        name="showForAllSafes"
                        type="checkbox"
                        label="Activate token for all Safes"
                      />
                    </Block>
                  </Col>
                  <Col align="center" layout="column" xs={6}>
                    <Paragraph className={classes.tokenImageHeading}>Token Image</Paragraph>
                    <Img alt="Token image" height={100} src={TokenPlaceholder} />
                  </Col>
                </Row>
              </Block>
              <Hairline />
              <Row align="center" className={classes.buttonRow}>
                <Button minHeight={42} minWidth={140} onClick={goBack}>
                  Cancel
                </Button>
                <Button color="primary" minHeight={42} minWidth={140} type="submit" variant="contained">
                  Save
                </Button>
              </Row>
            </>
          )
        }}
      </GnoForm>
    </>
  )
}
Example #24
Source File: index.tsx    From multisig-react with MIT License 4 votes vote down vote up
TokenList = (props: Props): React.ReactElement => {
  const classes = useStyles()
  const { setActiveScreen, tokens, activeTokens, blacklistedTokens, safeAddress } = props
  const [activeTokensAddresses, setActiveTokensAddresses] = useState(Set(activeTokens.map(({ address }) => address)))
  const [blacklistedTokensAddresses, setBlacklistedTokensAddresses] = useState<Set<string>>(blacklistedTokens)
  const [filter, setFilter] = useState('')
  const dispatch = useDispatch()

  const searchClasses = {
    input: classes.searchInput,
    root: classes.searchRoot,
    iconButton: classes.searchIcon,
    searchContainer: classes.searchContainer,
  }

  const onCancelSearch = () => {
    setFilter('')
  }

  const onChangeSearchBar = (value: string) => {
    setFilter(value)
  }

  const onSwitch = (token: Token) => () => {
    let newActiveTokensAddresses
    let newBlacklistedTokensAddresses
    if (activeTokensAddresses.has(token.address)) {
      newActiveTokensAddresses = activeTokensAddresses.delete(token.address)
      newBlacklistedTokensAddresses = blacklistedTokensAddresses.add(token.address)
    } else {
      newActiveTokensAddresses = activeTokensAddresses.add(token.address)
      newBlacklistedTokensAddresses = blacklistedTokensAddresses.delete(token.address)
    }

    // Set local state
    setActiveTokensAddresses(newActiveTokensAddresses)
    setBlacklistedTokensAddresses(newBlacklistedTokensAddresses)
    // Dispatch to global state
    dispatch(updateActiveTokens(safeAddress, newActiveTokensAddresses))
    dispatch(updateBlacklistedTokens(safeAddress, newBlacklistedTokensAddresses))
  }

  const createItemData = (tokens: List<Token>, activeTokensAddresses: Set<string>): ItemData => ({
    tokens,
    activeTokensAddresses,
    onSwitch,
  })

  const switchToAddCustomTokenScreen = () => setActiveScreen('addCustomToken')

  const getItemKey = (index: number, { tokens }): string => {
    return tokens.get(index).address
  }

  const filteredTokens = filterBy(filter, tokens)
  const itemData = createItemData(filteredTokens, activeTokensAddresses)

  return (
    <>
      <Block className={classes.root}>
        <Row align="center" className={cn(classes.padding, classes.actions)}>
          <Search className={classes.search} />
          <SearchBar
            classes={searchClasses}
            onCancelSearch={onCancelSearch}
            onChange={onChangeSearchBar}
            placeholder="Search by name or symbol"
            searchIcon={<div />}
            value={filter}
          />
          <Spacer />
          <Divider />
          <Spacer />
          <Button
            classes={{ label: classes.addBtnLabel }}
            className={classes.add}
            color="primary"
            onClick={switchToAddCustomTokenScreen}
            size="small"
            testId={ADD_CUSTOM_TOKEN_BUTTON_TEST_ID}
            variant="contained"
          >
            + Add custom token
          </Button>
        </Row>
        <Hairline />
      </Block>
      {!tokens.size && (
        <Block className={classes.progressContainer} justify="center">
          <CircularProgress />
        </Block>
      )}
      {tokens.size > 0 && (
        <MuiList className={classes.list}>
          <FixedSizeList
            height={413}
            itemCount={filteredTokens.size}
            itemData={itemData}
            itemKey={getItemKey}
            itemSize={51}
            overscanCount={process.env.NODE_ENV === 'test' ? 100 : 10}
            width={500}
          >
            {TokenRow}
          </FixedSizeList>
        </MuiList>
      )}
    </>
  )
}