Skip to content

Commit

Permalink
clients: update the init method on clients (#89)
Browse files Browse the repository at this point in the history
## Description

Updates the init method on the clients.

## Additional Information

Before submitting this issue, please make sure you do the following.

- [x] Added documentation related to the changes made.
- [x] Added or updated tests related to the changes made.
  • Loading branch information
Raiden1411 authored Aug 19, 2024
2 parents dc59f3d + ce9cf60 commit dbc1e3c
Show file tree
Hide file tree
Showing 26 changed files with 836 additions and 1,096 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,18 @@ pub fn main() !void {
var iter = try std.process.argsWithAllocator(gpa.allocator());
defer iter.deinit();
// Allocations are only made to pointer types.
const parsed = args_parser.parseArgs(CliOptions, gpa.allocator(), &iter);
const uri = try std.Uri.parse(parsed.url);
var wallet: Wallet = undefined;
try wallet.init(parsed.priv_key, .{ .allocator = gpa.allocator(), .uri = uri });
var wallet = try Wallet.init(parsed.priv_key, .{ .allocator = gpa.allocator(), .uri = uri });
defer wallet.deinit();
const message = try wallet.signEthereumMessage("Hello World");
const hexed = try message.toHex(wallet.allocator);
defer wallet.allocator.free(hexed);
defer gpa.allocator().free(hexed);
std.debug.print("Ethereum message: {s}\n", .{hexed});
}
```
Expand Down
9 changes: 4 additions & 5 deletions bench/benchmark.zig
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,13 @@ pub fn main() !void {
const allocator = std.heap.page_allocator;
const printer = BenchmarkPrinter.init(std.io.getStdErr().writer());

var client: HttpRpcClient = undefined;
defer client.deinit();

const uri = try std.Uri.parse("https://ethereum-rpc.publicnode.com");
try client.init(.{

var client = try HttpRpcClient.init(.{
.allocator = allocator,
.uri = uri,
});
defer client.deinit();

printer.print("{s}Benchmark running in {s} mode\n", .{ " " ** 20, @tagName(@import("builtin").mode) });
printer.print("\x1b[1;32m\n{s}\n{s}{s}\n{s}\n", .{ BORDER, PADDING, "Human-Readable ABI", BORDER });
Expand All @@ -83,7 +82,7 @@ pub fn main() !void {
const result = try benchmark.benchmark(
allocator,
HttpRpcClient.getChainId,
.{&client},
.{client},
.{ .runs = 5, .warmup_runs = 1 },
);
result.printSummary();
Expand Down
8 changes: 4 additions & 4 deletions docs/pages/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,18 @@ pub fn main() !void {
var iter = try std.process.argsWithAllocator(gpa.allocator());
defer iter.deinit();
// Allocations are only made to pointer types.
const parsed = args_parser.parseArgs(CliOptions, gpa.allocator(), &iter);
const uri = try std.Uri.parse(parsed.url);
var wallet: Wallet = undefined;
try wallet.init(parsed.priv_key, .{ .allocator = gpa.allocator(), .uri = uri });
var wallet = try Wallet.init(parsed.priv_key, .{ .allocator = gpa.allocator(), .uri = uri });
defer wallet.deinit();
const message = try wallet.signEthereumMessage("Hello World");
const hexed = try message.toHex(wallet.allocator);
defer wallet.allocator.free(hexed);
defer gpa.allocator().free(hexed);
std.debug.print("Ethereum message: {s}\n", .{hexed});
}
```
Expand Down
6 changes: 2 additions & 4 deletions examples/contract/contract.zig
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,15 @@ pub fn main() !void {
var abi_parsed = try human.parseHumanReadable(Abi, gpa.allocator(), slice);
defer abi_parsed.deinit();

var contract: Contract = undefined;
defer contract.deinit();

try contract.init(.{
var contract = try Contract.init(.{
.private_key = parsed.priv_key,
.abi = abi_parsed.value,
.wallet_opts = .{
.allocator = gpa.allocator(),
.uri = uri,
},
});
defer contract.deinit();

const approve = try contract.writeContractFunction("transfer", .{ try utils.addressToBytes("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"), 0 }, .{
.type = .london,
Expand Down
4 changes: 1 addition & 3 deletions examples/transfer/transfer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ pub fn main() !void {

const uri = try std.Uri.parse(parsed.url);

var wallet: Wallet = undefined;

try wallet.init(parsed.priv_key, .{
var wallet = try Wallet.init(parsed.priv_key, .{
.allocator = gpa.allocator(),
.uri = uri,
.chain_id = .sepolia,
Expand Down
5 changes: 3 additions & 2 deletions examples/wallet/wallet.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ pub fn main() !void {

const uri = try std.Uri.parse(parsed.url);

var wallet: Wallet = undefined;
try wallet.init(parsed.priv_key, .{ .allocator = gpa.allocator(), .uri = uri });
var wallet = try Wallet.init(parsed.priv_key, .{ .allocator = gpa.allocator(), .uri = uri });
defer wallet.deinit();

const message = try wallet.signEthereumMessage("Hello World");

const hexed = try message.toHex(wallet.allocator);
defer gpa.allocator().free(hexed);

std.debug.print("Ethereum message: {s}\n", .{hexed});
}
6 changes: 3 additions & 3 deletions examples/watch/logs.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const args_parser = zabi.args;
const std = @import("std");
const zabi = @import("zabi");

const WebSocket = zabi.clients.WebSocket;

pub const CliOptions = struct {
url: []const u8,
};
Expand All @@ -17,11 +19,9 @@ pub fn main() !void {

const uri = try std.Uri.parse(parsed.url);

var socket: zabi.clients.WebSocket = undefined;
var socket = try WebSocket.init(.{ .uri = uri, .allocator = gpa.allocator() });
defer socket.deinit();

try socket.init(.{ .uri = uri, .allocator = gpa.allocator() });

const id = try socket.watchLogs(.{
.address = try zabi.utils.addressToBytes("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
.topics = &.{@constCast(&try zabi.utils.hashToBytes("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"))},
Expand Down
6 changes: 3 additions & 3 deletions examples/watch/watch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const args_parser = zabi.args;
const std = @import("std");
const zabi = @import("zabi");

const WebSocket = zabi.clients.WebSocket;

pub const CliOptions = struct {
url: []const u8,
};
Expand All @@ -17,11 +19,9 @@ pub fn main() !void {

const uri = try std.Uri.parse(parsed.url);

var socket: zabi.clients.WebSocket = undefined;
var socket = try WebSocket.init(.{ .uri = uri, .allocator = gpa.allocator() });
defer socket.deinit();

try socket.init(.{ .uri = uri, .allocator = gpa.allocator() });

const id = try socket.watchTransactions();
defer id.deinit();

Expand Down
16 changes: 13 additions & 3 deletions src/clients/Client.zig
Original file line number Diff line number Diff line change
Expand Up @@ -142,26 +142,30 @@ const PubClient = @This();
/// Init the client instance. Caller must call `deinit` to free the memory.
/// Most of the client method are replicas of the JSON RPC methods name with the `eth_` start.
/// The client will handle request with 429 errors via exponential backoff but not the rest.
pub fn init(self: *PubClient, opts: InitOptions) !void {
pub fn init(opts: InitOptions) !*PubClient {
const chain: Chains = opts.chain_id orelse .ethereum;
const id = switch (chain) {
inline else => |id| @intFromEnum(id),
};

const self = try opts.allocator.create(PubClient);
errdefer opts.allocator.destroy(self);

self.* = .{
.uri = opts.uri,
.allocator = opts.allocator,
.chain_id = id,
.retries = opts.retries,
.pooling_interval = opts.pooling_interval,
.base_fee_multiplier = opts.base_fee_multiplier,
.client = http.Client{ .allocator = self.allocator },
.client = http.Client{ .allocator = opts.allocator },
.connection = undefined,
};

errdefer self.client.deinit();

self.connection = try self.connectRpcServer();

return self;
}
/// Clears the memory arena and destroys all pointers created
pub fn deinit(self: *PubClient) void {
Expand All @@ -179,10 +183,16 @@ pub fn deinit(self: *PubClient) void {

self.client = undefined;

const allocator = self.allocator;
allocator.destroy(self);

return;
}

self.client.deinit();

const allocator = self.allocator;
allocator.destroy(self);
}
/// Connects to the RPC server and relases the connection from the client pool.
/// This is done so that future fetchs can use the connection that is already freed.
Expand Down
14 changes: 11 additions & 3 deletions src/clients/IPC.zig
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,12 @@ sub_channel: Channel(JsonParsed(Value)),

/// Starts the IPC client and create the connection.
/// This will also start the read loop in a seperate thread.
pub fn init(self: *IPC, opts: InitOptions) !void {
pub fn init(opts: InitOptions) !*IPC {
const chain_id: Chains = opts.chain_id orelse .ethereum;

const self = try opts.allocator.create(IPC);
errdefer opts.allocator.destroy(self);

self.* = .{
.allocator = opts.allocator,
.base_fee_multiplier = opts.base_fee_multiplier,
Expand All @@ -163,8 +166,8 @@ pub fn init(self: *IPC, opts: InitOptions) !void {
.onEvent = opts.onEvent,
.pooling_interval = opts.pooling_interval,
.retries = opts.retries,
.rpc_channel = Stack(JsonParsed(Value)).init(self.allocator, null),
.sub_channel = Channel(JsonParsed(Value)).init(self.allocator),
.rpc_channel = Stack(JsonParsed(Value)).init(opts.allocator, null),
.sub_channel = Channel(JsonParsed(Value)).init(opts.allocator),
.ipc_reader = undefined,
};

Expand All @@ -185,6 +188,8 @@ pub fn init(self: *IPC, opts: InitOptions) !void {

const thread = try std.Thread.spawn(.{}, readLoopOwnedThread, .{self});
thread.detach();

return self;
}
/// Clears memory, closes the stream and destroys any
/// previously created pointers.
Expand All @@ -204,6 +209,9 @@ pub fn deinit(self: *IPC) void {
self.rpc_channel.deinit();
self.sub_channel.deinit();
self.ipc_reader.deinit();

const allocator = self.allocator;
allocator.destroy(self);
}
/// Connects to the socket. Will try to reconnect in case of failures.
/// Fails when match retries are reached or a invalid ipc path is provided
Expand Down
14 changes: 11 additions & 3 deletions src/clients/WebSocket.zig
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,12 @@ pub fn serverMessage(self: *WebSocketHandler, message: []u8, message_type: ws.Me

/// Populates the WebSocketHandler pointer.
/// Starts the connection in a seperate process.
pub fn init(self: *WebSocketHandler, opts: InitOptions) InitErrors!void {
pub fn init(opts: InitOptions) InitErrors!*WebSocketHandler {
const chain: Chains = opts.chain_id orelse .ethereum;

const self = try opts.allocator.create(WebSocketHandler);
errdefer opts.allocator.destroy(self);

self.* = .{
.allocator = opts.allocator,
.base_fee_multiplier = opts.base_fee_multiplier,
Expand All @@ -205,8 +208,8 @@ pub fn init(self: *WebSocketHandler, opts: InitOptions) InitErrors!void {
.onEvent = opts.onEvent,
.pooling_interval = opts.pooling_interval,
.retries = opts.retries,
.rpc_channel = Stack(JsonParsed(Value)).init(self.allocator, null),
.sub_channel = Channel(JsonParsed(Value)).init(self.allocator),
.rpc_channel = Stack(JsonParsed(Value)).init(opts.allocator, null),
.sub_channel = Channel(JsonParsed(Value)).init(opts.allocator),
.uri = opts.uri,
.ws_client = undefined,
};
Expand All @@ -220,6 +223,8 @@ pub fn init(self: *WebSocketHandler, opts: InitOptions) InitErrors!void {

const thread = try std.Thread.spawn(.{}, readLoopOwned, .{self});
thread.detach();

return self;
}
/// All future interactions will deadlock
/// If you are using the subscription channel this operation can take time
Expand All @@ -245,6 +250,9 @@ pub fn deinit(self: *WebSocketHandler) void {
self.sub_channel.deinit();
self.rpc_channel.deinit();
self.ws_client.deinit();

const allocator = self.allocator;
allocator.destroy(self);
}
/// Connects to a socket client. This is a blocking operation.
pub fn connect(self: *WebSocketHandler) ConnectionErrors!ws.Client {
Expand Down
Loading

0 comments on commit dbc1e3c

Please sign in to comment.