CAIP2.sol 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.2.0) (utils/CAIP2.sol)
  3. pragma solidity ^0.8.24;
  4. import {Bytes} from "./Bytes.sol";
  5. import {Strings} from "./Strings.sol";
  6. /**
  7. * @dev Helper library to format and parse CAIP-2 identifiers
  8. *
  9. * https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md[CAIP-2] defines chain identifiers as:
  10. * chain_id: namespace + ":" + reference
  11. * namespace: [-a-z0-9]{3,8}
  12. * reference: [-_a-zA-Z0-9]{1,32}
  13. *
  14. * WARNING: In some cases, multiple CAIP-2 identifiers may all be valid representation of a single chain.
  15. * For EVM chains, it is recommended to use `eip155:xxx` as the canonical representation (where `xxx` is
  16. * the EIP-155 chain id). Consider the possible ambiguity when processing CAIP-2 identifiers or when using them
  17. * in the context of hashes.
  18. */
  19. library CAIP2 {
  20. using Strings for uint256;
  21. using Bytes for bytes;
  22. /// @dev Return the CAIP-2 identifier for the current (local) chain.
  23. function local() internal view returns (string memory) {
  24. return format("eip155", block.chainid.toString());
  25. }
  26. /**
  27. * @dev Return the CAIP-2 identifier for a given namespace and reference.
  28. *
  29. * NOTE: This function does not verify that the inputs are properly formatted.
  30. */
  31. function format(string memory namespace, string memory ref) internal pure returns (string memory) {
  32. return string.concat(namespace, ":", ref);
  33. }
  34. /**
  35. * @dev Parse a CAIP-2 identifier into its components.
  36. *
  37. * NOTE: This function does not verify that the CAIP-2 input is properly formatted.
  38. */
  39. function parse(string memory caip2) internal pure returns (string memory namespace, string memory ref) {
  40. bytes memory buffer = bytes(caip2);
  41. uint256 pos = buffer.indexOf(":");
  42. return (string(buffer.slice(0, pos)), string(buffer.slice(pos + 1)));
  43. }
  44. }