Skip to content

Instantly share code, notes, and snippets.

@davidkathoh
Created June 7, 2024 16:57
Show Gist options
  • Save davidkathoh/36b453d7af8e2aef05675c1a2b34da7b to your computer and use it in GitHub Desktop.
Save davidkathoh/36b453d7af8e2aef05675c1a2b34da7b to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.26+commit.8a97fa7a.js&optimize=false&runs=200&gist=
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.2 <0.9.0;
/**
* @title Storage
* @dev Store & retrieve value in a variable
* @custom:dev-run-script ./scripts/deploy_with_ethers.ts
*/
contract C3Solana {
uint256 private constant OPERATOR_OFFSET = 0;
uint256 private constant AMOUNT_OFFSET = 20;
uint256 private constant MESSAGE_OFFSET = 52;
event MessageSent(bytes);
event MessageRecieved(address operator,
uint256 amount,
string message);
function send() external returns(bytes memory) {
Packet memory packet = Packet(0xe0591D75c9D882a911a37527656635E6537d3A6e, 1, "Hello World!");
bytes memory packetBytes = encode(packet);
emit MessageSent(packetBytes);
return packetBytes;
}
function receiveFromSolana(bytes calldata payload) external {
Packet memory packet = decode(payload);
emit MessageRecieved(packet.operator, packet.amount,packet.message);
}
struct Packet {
address operator;
uint256 amount;
string message;
}
function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {
return abi.encodePacked(
_packet.operator,
_packet.amount,
_packet.message
);
}
function decode(bytes calldata _encodedPacket) internal pure returns (Packet memory packet) {
packet.operator = decodeOperator(_encodedPacket);
packet.amount = decodeAmount(_encodedPacket);
packet.message = decodeMessage(_encodedPacket);
}
function decodeOperator(bytes calldata _encodedPacket) internal pure returns (address) {
require(_encodedPacket.length >= AMOUNT_OFFSET, "Invalid encoded packet");
return address(bytes20(_encodedPacket[OPERATOR_OFFSET:AMOUNT_OFFSET]));
}
function decodeAmount(bytes calldata _encodedPacket) internal pure returns (uint256) {
require(_encodedPacket.length >= MESSAGE_OFFSET, "Invalid encoded packet");
return uint256(bytes32(_encodedPacket[AMOUNT_OFFSET:MESSAGE_OFFSET]));
}
function decodeMessage(bytes calldata _encodedPacket) internal pure returns (string memory) {
require(_encodedPacket.length > MESSAGE_OFFSET, "Invalid encoded packet");
return string(_encodedPacket[MESSAGE_OFFSET:]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment