CAIP10.sol 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.2.0) (utils/CAIP10.sol)
  3. pragma solidity ^0.8.24;
  4. import {Bytes} from "./Bytes.sol";
  5. import {Strings} from "./Strings.sol";
  6. import {CAIP2} from "./CAIP2.sol";
  7. /**
  8. * @dev Helper library to format and parse CAIP-10 identifiers
  9. *
  10. * https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md[CAIP-10] defines account identifiers as:
  11. * account_id: chain_id + ":" + account_address
  12. * chain_id: [-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32} (See {CAIP2})
  13. * account_address: [-.%a-zA-Z0-9]{1,128}
  14. *
  15. * WARNING: According to [CAIP-10's canonicalization section](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md#canonicalization),
  16. * the implementation remains at the developer's discretion. Please note that case variations may introduce ambiguity.
  17. * For example, when building hashes to identify accounts or data associated to them, multiple representations of the
  18. * same account would derive to different hashes. For EVM chains, we recommend using checksummed addresses for the
  19. * "account_address" part. They can be generated onchain using {Strings-toChecksumHexString}.
  20. */
  21. library CAIP10 {
  22. using Strings for address;
  23. using Bytes for bytes;
  24. /// @dev Return the CAIP-10 identifier for an account on the current (local) chain.
  25. function local(address account) internal view returns (string memory) {
  26. return format(CAIP2.local(), account.toChecksumHexString());
  27. }
  28. /**
  29. * @dev Return the CAIP-10 identifier for a given caip2 chain and account.
  30. *
  31. * NOTE: This function does not verify that the inputs are properly formatted.
  32. */
  33. function format(string memory caip2, string memory account) internal pure returns (string memory) {
  34. return string.concat(caip2, ":", account);
  35. }
  36. /**
  37. * @dev Parse a CAIP-10 identifier into its components.
  38. *
  39. * NOTE: This function does not verify that the CAIP-10 input is properly formatted. The `caip2` return can be
  40. * parsed using the {CAIP2} library.
  41. */
  42. function parse(string memory caip10) internal pure returns (string memory caip2, string memory account) {
  43. bytes memory buffer = bytes(caip10);
  44. uint256 pos = buffer.lastIndexOf(":");
  45. return (string(buffer.slice(0, pos)), string(buffer.slice(pos + 1)));
  46. }
  47. }