CAIP2.sol 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {SafeCast} from "./math/SafeCast.sol";
  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. library CAIP2 {
  15. using SafeCast for uint256;
  16. using Strings for uint256;
  17. using Bytes for bytes;
  18. /// @dev Return the CAIP-2 identifier for the current (local) chain.
  19. function local() internal view returns (string memory) {
  20. return format("eip155", block.chainid.toString());
  21. }
  22. /**
  23. * @dev Return the CAIP-2 identifier for a given namespace and reference.
  24. *
  25. * NOTE: This function does not verify that the inputs are properly formatted.
  26. */
  27. function format(string memory namespace, string memory ref) internal pure returns (string memory) {
  28. return string.concat(namespace, ":", ref);
  29. }
  30. /**
  31. * @dev Parse a CAIP-2 identifier into its components.
  32. *
  33. * NOTE: This function does not verify that the CAIP-2 input is properly formatted.
  34. */
  35. function parse(string memory caip2) internal pure returns (string memory namespace, string memory ref) {
  36. bytes memory buffer = bytes(caip2);
  37. uint256 pos = buffer.indexOf(":");
  38. return (string(buffer.slice(0, pos)), string(buffer.slice(pos + 1)));
  39. }
  40. }