ronantakizawa/codereview-bench huggingface dataset:
Repository: unionlabs/union
File: hubble/src/token_list.rs (Rust)

Code before:
    pub major: i64,
    pub minor: i64,
    pub patch: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Token {
    pub chain_id: i64,
    pub address: String,
    pub name: String,
    pub symbol: String,
    pub decimals: i64,
    #[serde(rename = "logoURI")]
    pub logo_uri: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TokenInsert {
    pub chain_id: i64,
    pub denom: String,
    pub display_symbol: String,
    pub decimals: i64,
    pub logo_uri: Option<String>,
    pub display_name: String,
    pub gas_token: bool, // always false?
}

impl From<Token> for TokenInsert {
    fn from(token: Token) -> Self {
        TokenInsert {
            chain_id: token.chain_id,
            denom: token.address,
            display_symbol: token.symbol,
            decimals: token.decimals,
            logo_uri: token.logo_uri,
            display_name: token.name,
            gas_token: false,
        }
    }
}


Review comment (suggestion):
we should insert `false` on new records and keep the existing value if we're updating. so I think you best remove the field here and update the insert statement

Code after:
    pub logo_uri: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Version {
    pub major: i64,
    pub minor: i64,
    pub patch: i64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Token {
    pub chain_id: i64,
    pub address: String,
    pub name: String,
    pub symbol: String,
    pub decimals: i64,
    #[serde(rename = "logoURI")]
    pub logo_uri: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TokenInsert {
    pub chain_id: i64,
    pub denom: String,
    pub display_symbol: String,
    pub decimals: i64,
    pub logo_uri: Option<String>,
    pub display_name: String,
}

impl From<Token> for TokenInsert {
    fn from(token: Token) -> Self {
        TokenInsert {
            chain_id: token.chain_id,
            denom: token.address,
            display_symbol: token.symbol,
            decimals: token.decimals,
            logo_uri: token.logo_uri,
            display_name: token.name,
        }
    }
}
Repository: unionlabs/union
File: site/src/lib/matrix-cover.ts (TypeScript)

Code before:
  } else if (currentRotationDirection !== direction) {
    // If trying to rotate in opposite direction while rotating, ignore the new direction
    direction = currentRotationDirection
  }

  if (isRotating) {
    const rotationAmount = direction === "right" ? Math.PI / 2 : -Math.PI / 2
    targetPlaneRotation = initialRotation + rotationAmount * queuedRotations
  } else {
    isRotating = true
    rotationStartTime = performance.now()
    initialRotation = currentPlaneRotation
    targetPlaneRotation =
      currentPlaneRotation + (direction === "right" ? Math.PI / 2 : -Math.PI / 2)
  }
}

let canvas: HTMLCanvasElement
let mouseX = 0
let mouseY = 0
let targetMouseX = 0
let targetMouseY = 0
let displayWidth = 1000
let displayHeight = 1000
const RETINA_ENABLED = true
const WIDTH = 120 // Must be even
const endRotationY = Math.PI / 4 // Ending rotation angle
const endRotationX = Math.PI / 4 // Ending rotation angle

const W2 = WIDTH / 2

// Perlin noise implementation
class PerlinNoise {
  constructor() {
    this.permutation = new Array(512)
    this.p = new Array(256).fill(0).map((_, i) => i)
    for (let i = 255; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      ;[this.p[i], this.p[j]] = [this.p[j], this.p[i]]
    }
    for (let i = 0; i < 512; i++) {
      this.permutation[i] = this.p[i & 255]
    }
  }

  fade(t) {
    return t * t * t * (t * (t * 6 - 15) + 10)
  }

  lerp(t, a, b) {
    return a + t * (b - a)

Review comment (suggestion):
```suggestion
const WIDTH = 80 // Must be even
```

Code after:
  } else if (currentRotationDirection !== direction) {
    // If trying to rotate in opposite direction while rotating, ignore the new direction
    direction = currentRotationDirection
  }

  if (isRotating) {
    const rotationAmount = direction === "right" ? Math.PI / 2 : -Math.PI / 2
    targetPlaneRotation = initialRotation + rotationAmount * queuedRotations
  } else {
    isRotating = true
    rotationStartTime = performance.now()
    initialRotation = currentPlaneRotation
    targetPlaneRotation =
      currentPlaneRotation + (direction === "right" ? Math.PI / 2 : -Math.PI / 2)
  }
}

let canvas: HTMLCanvasElement
let mouseX = 0
let mouseY = 0
let targetMouseX = 0
let targetMouseY = 0
let displayWidth = 1000
let displayHeight = 1000
const RETINA_ENABLED = true
const WIDTH = 80 // Must be even
const endRotationY = Math.PI / 4 // Ending rotation angle
const endRotationX = Math.PI / 4 // Ending rotation angle

const W2 = WIDTH / 2

// Perlin noise implementation
class PerlinNoise {
  constructor() {
    this.permutation = new Array(512)
    this.p = new Array(256).fill(0).map((_, i) => i)
    for (let i = 255; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      ;[this.p[i], this.p[j]] = [this.p[j], this.p[i]]
    }
    for (let i = 0; i < 512; i++) {
      this.permutation[i] = this.p[i & 255]
    }
  }

  fade(t) {
    return t * t * t * (t * (t * 6 - 15) + 10)
  }

  lerp(t, a, b) {
    return a + t * (b - a)
Repository: unionlabs/union
File: lib/create3/src/lib.rs (Rust)

Code before:
use alloy_primitives::hex;
use sha3::{Digest, Keccak256};

const PROXY_INITCODE_HASH: [u8; 32] =
    hex!("21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f");

/// Use to obtain the address using the CREATE3 algorithm from solady's assembly optimized implementation
/// https://github.com/Vectorized/solady/blob/de9aee59648862bb98affd578248d1e75c7073ad/src/utils/CREATE3.sol#L106
pub fn predict_deterministic_address(deployer: &[u8], salt: &[u8; 32]) -> [u8; 20] {
    let mut bytes: Vec<u8> = Vec::new();
    bytes.push(0xff);
    bytes.extend_from_slice(deployer);
    bytes.extend_from_slice(salt);
    bytes.extend_from_slice(&PROXY_INITCODE_HASH);

    let hash = Keccak256::digest(&bytes);
    let mut proxy_bytes = [0u8; 20];
    proxy_bytes.copy_from_slice(&hash[12..]);

    // Use proxy address to compute the final contract address.
    // keccak256(rlp(proxy_bytes ++ 0x01)) More here -> https://ethereum.stackexchange.com/a/761/66849
    let mut bytes2: Vec<u8> = Vec::new();
    bytes2.extend_from_slice(&[0xd6, 0x94]);
    // RLP prefix for a list of two items
    bytes2.extend(&proxy_bytes);
    // The proxy address
    bytes2.push(0x01);
    // The nonce of the contract
    let hash2 = Keccak256::digest(&bytes2);

    // resulting hash -> The last 20 bytes (40 characters) of the hash.
    let mut address = [0u8; 20];
    address.copy_from_slice(&hash2[12..]);
    address

Review comment (suggestion):
deployer should be an address, salt should be b256, and this should return an address

https://docs.rs/alloy-primitives/latest/alloy_primitives/struct.Address.html
https://docs.rs/alloy-primitives/latest/alloy_primitives/aliases/type.B256.html

Code after:
use alloy_primitives::{hex, Address, B256};
use sha3::{Digest, Keccak256};

const PROXY_INITCODE_HASH: [u8; 32] =
    hex!("21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f");

/// Use to obtain the address using the CREATE3 algorithm from solady's assembly optimized implementation
/// https://github.com/Vectorized/solady/blob/de9aee59648862bb98affd578248d1e75c7073ad/src/utils/CREATE3.sol#L106
pub fn predict_deterministic_address(deployer: Address, salt: B256) -> Address {
    let mut bytes: Vec<u8> = Vec::new();
    bytes.push(0xff);
    bytes.extend_from_slice(deployer.as_slice());
    bytes.extend_from_slice(salt.as_slice());
    bytes.extend_from_slice(&PROXY_INITCODE_HASH);

    let hash = Keccak256::digest(&bytes);
    let mut proxy_bytes = [0u8; 20];
    proxy_bytes.copy_from_slice(&hash[12..]);

    // Use proxy address to compute the final contract address.
    // keccak256(rlp(proxy_bytes ++ 0x01)) More here -> https://ethereum.stackexchange.com/a/761/66849
    let mut bytes2: Vec<u8> = Vec::new();
    bytes2.extend_from_slice(&[0xd6, 0x94]);
    // RLP prefix for a list of two items
    bytes2.extend(&proxy_bytes);
    // The proxy address
    bytes2.push(0x01);
    // The nonce of the contract
    let hash2 = Keccak256::digest(&bytes2);

    // resulting hash -> The last 20 bytes (40 characters) of the hash.
    Address::from_slice(&hash2[12..])
}
Repository: unionlabs/union
File: lib/trusted-mpt-light-client-types/src/signed_data.rs (Rust)

Code before:
use unionlabs::{
    encoding::{Encode, Encoding},
    primitives::{H256, H512},
};

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
pub struct SignedData<T> {
    data: T,
    signature: H512,
}

pub struct SignatureVerificationFailure;

impl<T: Clone> SignedData<T> {
    pub fn sign<E, V: Fn(&[u8]) -> H512>(data: T, sign: V) -> Self
    where
        E: Encoding,
        for<'a> &'a T: Encode<E>,
    {
        SignedData {
            signature: sign(&data.encode()),
            data,
        }
    }

    pub fn unwrap_verified<E, V: Fn(&[u8], H512, H256) -> Option<bool>>(
        self,
        pubkey: H256,
        verify_sig: V,
    ) -> Result<T, SignatureVerificationFailure>
    where
        E: Encoding,
        for<'a> &'a T: Encode<E>,
    {
        if verify_sig(&self.data.encode(), self.signature, pubkey)
            .ok_or(SignatureVerificationFailure)?
        {

Review comment (suggestion):
another small nit, let's make an issue for it to be done later: this type could be generic over the signature size as well. we could then look into moving this type into somewhere more generic. for now this is fine though

Code after:
use core::fmt::Display;

use thiserror::Error;
use unionlabs::{
    encoding::{Encode, Encoding},
    primitives::{H256, H512},
};

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
pub struct SignedData<T> {
    data: T,
    signature: H512,
}

#[derive(Debug, Error)]
pub struct SignatureVerificationFailure;

impl Display for SignatureVerificationFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "signature verification failure")
    }
}

impl<T: Clone> SignedData<T> {
    pub fn sign<E, V>(data: T, sign: V) -> Self
    where
        E: Encoding,
        for<'a> &'a T: Encode<E>,
        V: Fn(&[u8]) -> H512,
    {
        SignedData {
            signature: sign(&data.encode()),
            data,
        }
    }

    pub fn unwrap_verified<E, V>(
Repository: unionlabs/union
File: app2/src/lib/queries/transfer-by-hash.svelte.ts (TypeScript)

Code before:
          transfer_send_timestamp
          transfer_recv_timestamp
          base_token
          base_amount
          quote_amount
          quote_token
          success
          traces {
            type
            height
            block_hash
            timestamp
            transaction_hash
            chain {
              universal_chain_id
            }
          }
        }
      }
    `),
    variables: { packet_hash: packetHash },
    refetchInterval: "1 second",
    writeData: data => {
      if (data.pipe(Option.map(d => d.v2_transfers.length)).pipe(Option.getOrElse(() => 0)) === 0) {
        transferDetails.error = Option.some(new NoSuchElementException())
      }
      transferDetails.data = data.pipe(Option.map(d => d.v2_transfers[0]))
    },
    writeError: error => {
      transferDetails.error = error
    },
  })


Review comment (suggestion):
This already exists. We'll eventually move away from `NoSuchElementException` by mapping onto our own types so this class of errors has meaningful context.

Code after:
          transfer_send_timestamp
          transfer_recv_timestamp
          transfer_timeout_transaction_hash
          base_token
          base_amount
          quote_amount
          quote_token
          success
          traces {
            type
            height
            block_hash
            timestamp
            transaction_hash
            chain {
              universal_chain_id
            }
          }
        }
      }
    `),
    variables: { packet_hash: packetHash },
    refetchInterval: "1 second",
    writeData: data => {
      if (data.pipe(Option.map(d => d.v2_transfers.length)).pipe(Option.getOrElse(() => 0)) === 0) {
        transferDetails.error = Option.some(new NoSuchElementException())
      }
      transferDetails.data = data.pipe(Option.map(d => d.v2_transfers[0]))
    },
    writeError: error => {
      transferDetails.error = error
    },
  })
Repository: unionlabs/union
File: app2/src/lib/dashboard/client.ts (TypeScript)

Code before:
export type SupabaseOptions = NonNullable<Parameters<typeof createClient<Database>>[2]>

export class SupabaseClient extends Effect.Service<SupabaseClient>()("SupabaseClient", {
  scoped: (options?: SupabaseOptions | undefined) =>
    Effect.gen(function*() {
      const url = yield* S.decode(S.URL)(PUBLIC_SUPABASE_URL).pipe(
        Effect.mapError((cause) =>
          new SupabaseClientError({
            operation: "init",
            message: "Could not decode PUBLIC_SUPABASE_URL to URL",
            cause,
          })
        ),
      )
      const anonKey = yield* S.decode(S.NonEmptyString)(PUBLIC_SUPABASE_ANON_KEY).pipe(
        Effect.mapError((cause) =>
          new SupabaseClientError({
            operation: "init",
            message: "Could not decode PUBLIC_SUPABASE_ANON_KEY to non-empty string",
            cause,
          })
        ),
      )

      return createClient<Database>(url.toString(), anonKey, options)
    }),
}) {}


Review comment (bug):
This service provides the `SupabaseClient` from `@supabase/supabase-js` without any indirection.

This Effect service will guarantee that the Supabase client is initialized with the `AppRuntime` layer, which will remove possibility of race conditions.

Code after:
export type SupabaseOptions = NonNullable<Parameters<typeof createClient<Database>>[2]>

export class SupabaseClient extends Effect.Service<SupabaseClient>()("SupabaseClient", {
  scoped: Effect.fnUntraced(function*(options?: SupabaseOptions | undefined) {
    const url = yield* S.decode(S.URL)(PUBLIC_SUPABASE_URL).pipe(
      Effect.mapError((cause) =>
        new SupabaseClientError({
          operation: "init",
          message: "Could not decode PUBLIC_SUPABASE_URL to URL",
          cause,
        })
      ),
    )
    const anonKey = yield* S.decode(S.NonEmptyString)(PUBLIC_SUPABASE_ANON_KEY).pipe(
      Effect.mapError((cause) =>
        new SupabaseClientError({
          operation: "init",
          message: "Could not decode PUBLIC_SUPABASE_ANON_KEY to non-empty string",
          cause,
        })
      ),
    )

    return createClient<Database>(url.toString(), anonKey, options)
  }),
}) {}
Repository: vercel-labs/ai
File: packages/ai/src/agent/create-agent-ui-stream.ts (TypeScript)

Code before:
  >
> {
  const validatedMessages = await validateUIMessages<
    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>
  >({
    messages: uiMessages,
    tools: agent.tools,
  });

  const modelMessages = await convertToModelMessages(validatedMessages, {
    tools: agent.tools,
  });

  const result = await agent.stream({
    prompt: modelMessages,
    options: options as CALL_OPTIONS,
    abortSignal,
    timeout,
    experimental_transform,
    onStepFinish,
  });

  return result.toUIMessageStream({
    ...uiMessageStreamOptions,
    originalMessages:
      uiMessageStreamOptions.originalMessages ?? validatedMessages,
  });
}


Review comment (suggestion):
If we wanted to make this change more cautiously, we could choose to only auto-populate if `onFinish` is also provided - that would drastically reduce the surface area of the change.

It doesn't make too much sense to me to limit it to only `onFinish`, but if there are concerns, we could start with that. That said, the tests and the effective changes suggest to me that changing this should be fine.

Code after:
  const validatedMessages = await validateUIMessages<
    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>
  >({
    messages: uiMessages,
    tools: agent.tools,
  });

  const modelMessages = await convertToModelMessages(validatedMessages, {
    tools: agent.tools,
  });

  const result = await agent.stream({
    prompt: modelMessages,
    options: options as CALL_OPTIONS,
    abortSignal,
    timeout,
    experimental_transform,
    onStepFinish,
  });

  return result.toUIMessageStream({
    ...uiMessageStreamOptions,
    // TODO reading `originalMessages` is here for bc, always use `validatedMessages` in v7
    originalMessages:
      uiMessageStreamOptions.originalMessages ?? validatedMessages,
  });
}
Repository: vercel-labs/ai
File: packages/ai/src/model/resolve-model.ts (TypeScript)

Code before:
        modelId: unsupportedModel.modelId,
      });
    }

    return asImageModelV3(model);
  }

  return getGlobalProvider().imageModel(model);
}

export function resolveVideoModel(
  model: VideoModel,
): Experimental_VideoModelV3 {
  if (typeof model === 'string') {
    const provider = getGlobalProvider();
    // TODO AI SDK v7
    // @ts-expect-error - videoModel support is experimental
    if (!provider.videoModel) {
      throw new Error(
        'The default provider does not support video models. ' +
          'Please use a Experimental_VideoModelV3 object from a provider (e.g., fal.video("model-id")).',
      );
    }
    // TODO AI SDK v7
    // @ts-expect-error - videoModel support is experimental
    return provider.videoModel(model);
  }

  if (model.specificationVersion !== 'v3') {
    const unsupportedModel: any = model;
    throw new UnsupportedModelVersionError({
      version: unsupportedModel.specificationVersion,
      provider: unsupportedModel.provider,
      modelId: unsupportedModel.modelId,
    });
  }

  return model;
}

function getGlobalProvider(): ProviderV3 {
  return globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;
}


Review comment (suggestion):
```suggestion
    // TODO AI SDK v7
    // @ts-expect-error - videoModel support is experimental
    const videoModel = provider.videoModel

    if (!videoModel) {
      throw new Error(
        'The default provider does not support video models. ' +
          'Please use a Experimental_VideoModelV3 object from a provider (e.g., fal.video("model-id")).',
      );
    }

    return videoModel(model);
```

Code after:
        modelId: unsupportedModel.modelId,
      });
    }

    return asImageModelV3(model);
  }

  return getGlobalProvider().imageModel(model);
}

export function resolveVideoModel(
  model: VideoModel,
): Experimental_VideoModelV3 {
  if (typeof model === 'string') {
    const provider = getGlobalProvider();
    // TODO AI SDK v7
    // @ts-expect-error - videoModel support is experimental
    const videoModel = provider.videoModel;

    if (!videoModel) {
      throw new Error(
        'The default provider does not support video models. ' +
          'Please use a Experimental_VideoModelV3 object from a provider (e.g., vertex.video("model-id")).',
      );
    }

    return videoModel(model);
  }

  if (model.specificationVersion !== 'v3') {
    const unsupportedModel: any = model;
    throw new UnsupportedModelVersionError({
      version: unsupportedModel.specificationVersion,
      provider: unsupportedModel.provider,
      modelId: unsupportedModel.modelId,
    });
  }

  return model;
}

function getGlobalProvider(): ProviderV3 {
  return globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;
}
Repository: web-infra-dev/midscene
File: packages/shared/src/env/parse-model-config.ts (TypeScript)

Code before:
import {
  DEFAULT_MODEL_CONFIG_KEYS,
  type DEFAULT_MODEL_CONFIG_KEYS_LEGACY,
  INSIGHT_MODEL_CONFIG_KEYS,
  PLANNING_MODEL_CONFIG_KEYS,
} from './constants';
import {
  type IModelConfig,
  MIDSCENE_MODEL_FAMILY,
  MIDSCENE_OPENAI_HTTP_PROXY,
  MIDSCENE_OPENAI_INIT_CONFIG_JSON,
  MIDSCENE_OPENAI_SOCKS_PROXY,
  MIDSCENE_USE_DOUBAO_VISION,
  MIDSCENE_USE_GEMINI,
  MIDSCENE_USE_GLM_V,
  MIDSCENE_USE_QWEN3_VL,
  MIDSCENE_USE_QWEN_VL,
  MIDSCENE_USE_VLM_UI_TARS,
  MODEL_FAMILY_VALUES,
  OPENAI_API_KEY,
  OPENAI_BASE_URL,
  type TIntent,
  type TModelFamily,
  type TVlModeTypes,
  UITarsModelVersion,
} from './types';

import { getDebug } from '../logger';
import { assert } from '../utils';
import { maskConfig, parseJson } from './helper';
import { initDebugConfig } from './init-debug';

type TModelConfigKeys =
  | typeof INSIGHT_MODEL_CONFIG_KEYS
  | typeof PLANNING_MODEL_CONFIG_KEYS
  | typeof DEFAULT_MODEL_CONFIG_KEYS
  | typeof DEFAULT_MODEL_CONFIG_KEYS_LEGACY;

const KEYS_MAP: Record<TIntent, TModelConfigKeys> = {
  insight: INSIGHT_MODEL_CONFIG_KEYS,

Review comment (suggestion):
The `MIDSCENE_USE_GLM_V` is useless here. You can remove it.

These `MIDSCENE_USE_...` configs are for backward compatibility with 0.x versions

Code after:
import {
  DEFAULT_MODEL_CONFIG_KEYS,
  type DEFAULT_MODEL_CONFIG_KEYS_LEGACY,
  INSIGHT_MODEL_CONFIG_KEYS,
  PLANNING_MODEL_CONFIG_KEYS,
} from './constants';
import {
  type IModelConfig,
  MIDSCENE_MODEL_FAMILY,
  MIDSCENE_OPENAI_HTTP_PROXY,
  MIDSCENE_OPENAI_INIT_CONFIG_JSON,
  MIDSCENE_OPENAI_SOCKS_PROXY,
  MIDSCENE_USE_DOUBAO_VISION,
  MIDSCENE_USE_GEMINI,
  MIDSCENE_USE_QWEN3_VL,
  MIDSCENE_USE_QWEN_VL,
  MIDSCENE_USE_VLM_UI_TARS,
  MODEL_FAMILY_VALUES,
  OPENAI_API_KEY,
  OPENAI_BASE_URL,
  type TIntent,
  type TModelFamily,
  type TVlModeTypes,
  UITarsModelVersion,
} from './types';

import { getDebug } from '../logger';
import { assert } from '../utils';
import { maskConfig, parseJson } from './helper';
import { initDebugConfig } from './init-debug';

type TModelConfigKeys =
  | typeof INSIGHT_MODEL_CONFIG_KEYS
  | typeof PLANNING_MODEL_CONFIG_KEYS
  | typeof DEFAULT_MODEL_CONFIG_KEYS
  | typeof DEFAULT_MODEL_CONFIG_KEYS_LEGACY;

const KEYS_MAP: Record<TIntent, TModelConfigKeys> = {
  insight: INSIGHT_MODEL_CONFIG_KEYS,
  planning: PLANNING_MODEL_CONFIG_KEYS,