From 104f5f2b84bd6c09feca4ee956fa8ec67a4c434f Mon Sep 17 00:00:00 2001 From: 0xDeon <110722148+0xDeon@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:17:53 +0100 Subject: [PATCH] feat(dapp): send avalanche naira off-ramps to linq, weave only when linq can't take one Linq now takes Circle's native USDC on the Avalanche C-Chain. An Avalanche naira off-ramp is placed with Linq the way Sui and Solana are, and falls back to Weave only for a bank Linq doesn't know or an order it refuses. The order Linq returns must name the avalanche chain, native USDC's contract, a C-Chain deposit address and exactly the USDC asked; the refund address goes checksummed. --- apps/dapp/app/api/cashout/quote/route.ts | 4 +- apps/dapp/lib/__tests__/linq-client.test.ts | 71 ++++++++++++ .../lib/__tests__/linq-sui-cashout.test.ts | 102 +++++++++++++++++- .../lib/__tests__/weave-best-payout.test.ts | 17 ++- apps/dapp/lib/linq/client.ts | 39 ++++++- apps/dapp/lib/support/assistant.ts | 2 +- apps/dapp/lib/weave/best-payout.ts | 2 +- apps/dapp/lib/weave/deposit/avalanche.ts | 3 +- apps/dapp/lib/weave/linq-cashout.ts | 9 +- 9 files changed, 226 insertions(+), 23 deletions(-) diff --git a/apps/dapp/app/api/cashout/quote/route.ts b/apps/dapp/app/api/cashout/quote/route.ts index 4d61b893..b72051ba 100644 --- a/apps/dapp/app/api/cashout/quote/route.ts +++ b/apps/dapp/app/api/cashout/quote/route.ts @@ -20,7 +20,7 @@ function refuse(error: string, message: string): Response { /** * What a cash-out would pay, what it would cost, and how long it should take. * - * A naira cash-out from Sui or Solana is priced by whichever of Weave and Linq pays more, as the + * A naira cash-out from Sui, Solana or Avalanche is priced by whichever of Weave and Linq pays more, as the * order route places it. Linq's figure is the naira it pays; it states no fee of its own. */ export async function GET(request: Request): Promise { @@ -45,7 +45,7 @@ export async function GET(request: Request): Promise { const result = await createWeaveClient().quote({ chain, currency, amount }) const linq = createLinqClient() - // Sui and Solana naira go to Linq whenever it answers, so its locked rate is what is shown. + // Sui, Solana and Avalanche naira go to Linq whenever it answers, so its locked rate is what is shown. if (comparesLinq(chain) && currency === 'NGN' && linq.configured) { const rate = await linq.getRate().catch(() => undefined) const naira = rate?.ok === true ? rate.value.ngnPerUsd * Number(amount) : Number.NaN diff --git a/apps/dapp/lib/__tests__/linq-client.test.ts b/apps/dapp/lib/__tests__/linq-client.test.ts index 392015eb..638bf2f7 100644 --- a/apps/dapp/lib/__tests__/linq-client.test.ts +++ b/apps/dapp/lib/__tests__/linq-client.test.ts @@ -245,6 +245,77 @@ describe('linq client', () => { expect(xlm.calls).toHaveLength(0) }) + it('orders USDC on Avalanche, held to the C-Chain, native USDC and exactly the USDC asked', async () => { + const NATIVE_USDC = '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E' + const AVAX_DEPOSIT = `0x${'7a'.repeat(20)}` + const avax = { + ...usdcBase, + chain: 'avalanche' as const, + amountStableCoin: 1.25, + refundAddress: '0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6f', + } + const answer = (over: Record = {}) => + goodOrder({ + chain: 'avalanche', + coin: 'usdc', + coinType: NATIVE_USDC, + walletAddress: AVAX_DEPOSIT, + amountStableCoin: 1.25, + amountNGN: 1710.48, + ...over, + }) + + const good = server(() => ({ status: 201, body: answer() })) + expect( + await createLinqClient({ ...config, fetchImpl: good.fetchImpl }).createOrder(avax) + ).toMatchObject({ + ok: true, + value: { depositAddress: AVAX_DEPOSIT, amountCoin: 1.25, amountNGN: 1710.48 }, + }) + // Linq refuses a refund address with a bad checksum, so it goes checksummed. + expect(JSON.parse(good.calls[0]?.init.body ?? '{}')).toMatchObject({ + chain: 'avalanche', + coin: 'usdc', + amountStableCoin: 1.25, + manualDeposit: true, + refundAddress: '0xb97ef9Ef8734C71904d8002F8B6BC66dd9c48A6F', + }) + + for (const right of [{ coinType: NATIVE_USDC.toLowerCase() }, { coin: undefined }]) { + const ok = server(() => ({ status: 201, body: answer(right) })) + expect( + await createLinqClient({ ...config, fetchImpl: ok.fetchImpl }).createOrder(avax) + ).toMatchObject({ ok: true }) + } + + for (const wrong of [ + { chain: 'solana' }, + { coinType: '0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664' }, + { coinType: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7' }, + { coinType: '' }, + { coin: 'usdt' }, + { walletAddress: DEPOSIT }, + { walletAddress: `0x${'ab'.repeat(32)}` }, + { walletAddress: `0x${'00'.repeat(20)}` }, + { walletAddress: NATIVE_USDC }, + { amountStableCoin: 1.26 }, + ]) { + const bad = server(() => ({ status: 201, body: answer(wrong) })) + expect( + await createLinqClient({ ...config, fetchImpl: bad.fetchImpl }).createOrder(avax) + ).toMatchObject({ ok: false, code: 'unexpected_order' }) + } + + const notEvm = server(() => ({ status: 201, body: answer() })) + expect( + await createLinqClient({ ...config, fetchImpl: notEvm.fetchImpl }).createOrder({ + ...avax, + refundAddress: REFUND, + }) + ).toMatchObject({ ok: false, code: 'rejected' }) + expect(notEvm.calls).toHaveLength(0) + }) + it('checks a USDC trustline, and treats an unreachable ledger as unknown', async () => { const yes = server(() => ({ status: 200, body: { valid: true, trustsUSDC: true } })) expect( diff --git a/apps/dapp/lib/__tests__/linq-sui-cashout.test.ts b/apps/dapp/lib/__tests__/linq-sui-cashout.test.ts index cf584071..8b79a577 100644 --- a/apps/dapp/lib/__tests__/linq-sui-cashout.test.ts +++ b/apps/dapp/lib/__tests__/linq-sui-cashout.test.ts @@ -38,6 +38,8 @@ const WALLET = `0x${'2c'.repeat(32)}` const LINQ_DEPOSIT = `0x${'ab'.repeat(32)}` const SOLANA_WALLET = '7EcDhSYGxXyscszYEp35KHN8vvw3svAuLKTzXwCFLtV' const SOLANA_LINQ_DEPOSIT = '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM' +const AVALANCHE_WALLET = `0x${'4e'.repeat(20)}` +const AVALANCHE_LINQ_DEPOSIT = `0x${'7a'.repeat(20)}` const DIGITS = '8100003682' const HOLDER = 'JANE ADEYEMI' @@ -208,7 +210,7 @@ describe('placeWithLinq', () => { it.each([ ['another currency', { currency: 'KES' }, 'not_offered'], - ['another chain', { chain: 'avalanche' }, 'not_offered'], + ['another chain', { chain: 'near' }, 'not_offered'], ])('asks Linq nothing for %s', async (_name, over, reason) => { expect(await placeWithLinq(input(over))).toEqual({ skipped: reason }) expect(called(state.linq['getRate'])).not.toHaveBeenCalled() @@ -224,6 +226,16 @@ describe('placeWithLinq', () => { ) }) + it('places an Avalanche USDC order on Avalanche, refunding to the C-Chain wallet', async () => { + const placed = await placeWithLinq( + input({ chain: 'avalanche', refundAddress: AVALANCHE_WALLET, customerRef: 'wallet:avax' }) + ) + expect(placed).toEqual({ placed: linqOrder }) + expect(called(state.linq['createOrder'])).toHaveBeenCalledWith( + expect.objectContaining({ chain: 'avalanche', coin: 'usdc', refundAddress: AVALANCHE_WALLET }) + ) + }) + it('asks Linq nothing when it is not configured', async () => { state.linq = linq({ configured: false }) expect(await placeWithLinq(input())).toEqual({ skipped: 'not_offered' }) @@ -455,8 +467,89 @@ describe('POST order, naira from Solana', () => { }) }) -describe('GET quote, naira from Solana', () => { - it("shows Linq's naira when Linq pays more, and leaves Avalanche with Weave", async () => { +describe('POST order, naira from Avalanche', () => { + const postFromAvalanche = (currency = 'NGN'): Request => + new Request('http://localhost/api/cashout/orders', { + method: 'POST', + headers: { 'Content-Type': 'application/json', [WALLET_HEADER]: AVALANCHE_WALLET }, + body: JSON.stringify({ + chain: 'avalanche', + account: AVALANCHE_WALLET, + amount: '1', + currency, + institution: 'OPAYNGPC', + accountIdentifier: DIGITS, + idempotencyKey: KEY, + }), + }) + + const weaveOnAvalanche = (over: Record = {}) => + weave({ + createOrder: vi.fn(async () => ({ + ok: true, + value: { + ...weaveOrder, + sourceAssetKey: 'crypto:AVALANCHE:USDC', + deposit: { ...weaveOrder.deposit, address: `0x${'cd'.repeat(20)}`, chain: 'AVALANCHE' }, + }, + })), + ...over, + }) + + beforeEach(() => { + state.deposit = { ...state.deposit, isAccount: () => true, isDepositAddress: () => true } + state.weave = weaveOnAvalanche() + state.linq = linq({ + createOrder: vi.fn(async () => ({ + ok: true, + value: { ...linqOrder, depositAddress: AVALANCHE_LINQ_DEPOSIT }, + })), + }) + }) + + it('places it with Linq on Avalanche, and stores the naira Linq locked', async () => { + expect((await POST(postFromAvalanche())).status).toBe(200) + expect(called(state.linq['createOrder'])).toHaveBeenCalledWith( + expect.objectContaining({ chain: 'avalanche', refundAddress: AVALANCHE_WALLET }) + ) + expect(called(state.repo['insert']).mock.calls[0]?.[0]).toMatchObject({ + chain: 'avalanche', + provider: 'linq', + depositAddress: AVALANCHE_LINQ_DEPOSIT, + estimatedDest: '1368.39', + }) + expect(called(state.weave['createOrder'])).not.toHaveBeenCalled() + }) + + it('places it with Linq even when Weave would pay more', async () => { + state.weave = weaveOnAvalanche({ + quote: vi.fn(async () => ({ + ok: true, + value: { destAmount: 1400, netUsd: 0.99, seconds: 90 }, + })), + }) + expect((await POST(postFromAvalanche())).status).toBe(200) + expect(called(state.weave['createOrder'])).not.toHaveBeenCalled() + expect(called(state.repo['insert']).mock.calls[0]?.[0]).toMatchObject({ provider: 'linq' }) + }) + + it('falls back to Weave, and reports it, when Linq answers with a different order', async () => { + state.linq = linq({ + createOrder: vi.fn(async () => ({ ok: false, code: 'unexpected_order', message: 'x' })), + }) + expect((await POST(postFromAvalanche())).status).toBe(200) + expect(called(state.repo['insert']).mock.calls[0]?.[0]).toMatchObject({ provider: 'weave' }) + expect(state.report.map((r) => String(r[1]))).toContain('Error: linq_order_unexpected') + }) + + it('keeps another currency with Weave, asking Linq nothing', async () => { + await POST(postFromAvalanche('KES')) + expect(called(state.linq['createOrder'])).not.toHaveBeenCalled() + }) +}) + +describe('GET quote, naira from Solana and Avalanche', () => { + it("shows Linq's naira on both, and leaves NEAR with Weave", async () => { const ask = (chain: string) => quote( new Request(`http://localhost/api/cashout/quote?chain=${chain}¤cy=NGN&amount=1`, { @@ -468,7 +561,8 @@ describe('GET quote, naira from Solana', () => { costPercent: 0, seconds: 90, }) - expect((await (await ask('avalanche')).json()).destAmount).not.toBe(1368.39) + expect((await (await ask('avalanche')).json()).destAmount).toBe(1368.39) + expect((await (await ask('near')).json()).destAmount).not.toBe(1368.39) }) }) diff --git a/apps/dapp/lib/__tests__/weave-best-payout.test.ts b/apps/dapp/lib/__tests__/weave-best-payout.test.ts index 9f204e48..dbdaebd0 100644 --- a/apps/dapp/lib/__tests__/weave-best-payout.test.ts +++ b/apps/dapp/lib/__tests__/weave-best-payout.test.ts @@ -15,11 +15,18 @@ describe('nairaOffers', () => { ]) expect(onStellar.weaveNaira).not.toHaveBeenCalled() - const onAvalanche = sources(1368.39, 916.44) - expect(await nairaOffers('avalanche', '0.689418', onAvalanche)).toEqual([ + const onNear = sources(1368.39, 916.44) + expect(await nairaOffers('near', '0.689418', onNear)).toEqual([ { provider: 'weave', naira: 916.44, exact: false }, ]) - expect(onAvalanche.linqRate).not.toHaveBeenCalled() + expect(onNear.linqRate).not.toHaveBeenCalled() + }) + + it('asks both on Avalanche, where each can pay, best first', async () => { + expect(await nairaOffers('avalanche', '1', sources(1368.39, 1329.29))).toEqual([ + { provider: 'linq', naira: 1368.39, exact: true }, + { provider: 'weave', naira: 1329.29, exact: false }, + ]) }) it('gives no offer for a provider that cannot be read, rather than a guess', async () => { @@ -50,8 +57,8 @@ describe('nairaOffers', () => { ]) }) - it('pays naira from Linq on Stellar, Sui and Solana, and from Weave on NEAR but not Stellar', () => { - expect(PAYS_NAIRA.linq).toEqual(['stellar', 'sui', 'solana']) + it('pays naira from Linq on Stellar, Sui, Solana and Avalanche, and from Weave on NEAR but not Stellar', () => { + expect(PAYS_NAIRA.linq).toEqual(['stellar', 'sui', 'solana', 'avalanche']) expect(PAYS_NAIRA.weave).not.toContain('stellar') expect(PAYS_NAIRA.weave).toContain('near') }) diff --git a/apps/dapp/lib/linq/client.ts b/apps/dapp/lib/linq/client.ts index 8abeeeac..95a8cc20 100644 --- a/apps/dapp/lib/linq/client.ts +++ b/apps/dapp/lib/linq/client.ts @@ -2,6 +2,9 @@ import { createHmac, timingSafeEqual } from 'node:crypto' import { isAddress } from '@solana/kit' import { StrKey } from '@stellar/stellar-sdk' +import { getAddress, isAddress as isEvmAddress, zeroAddress } from 'viem' + +import { AVALANCHE_USDC } from '../weave/deposit/avalanche' /** * Server-side client for the Linq B2B off-ramp: XLM or USDC in, naira to a bank. @@ -10,7 +13,7 @@ import { StrKey } from '@stellar/stellar-sdk' * reached from route handlers. Nothing here is imported by a client component. * * Every order has `manualDeposit: true`, in native XLM or USDC on Stellar and - * USDC on Sui and Solana, so the payout follows what actually arrives and a + * USDC on Sui, Solana and Avalanche, so the payout follows what actually arrives and a * short payment is never a loss for the operator. */ @@ -31,9 +34,10 @@ export type LinqCoin = 'xlm' | 'usdc' /** * Where a Linq order takes its deposit. Linq's dashboard docs list `sui` (USDSUI, USDC), `solana` - * (USDC) and `stellar` (USDC, XLM) among others; only these three are ordered from here. + * (USDC), `stellar` (USDC, XLM) and, from 16 November 2026, `avalanche` (USDC, USDT on the C-Chain) + * among others; only these four are ordered from here. */ -export type LinqChain = 'stellar' | 'sui' | 'solana' +export type LinqChain = 'stellar' | 'sui' | 'solana' | 'avalanche' /** A Sui account or object address: 0x and 64 hex digits. */ const SUI_ADDRESS = /^0x[0-9a-fA-F]{64}$/ @@ -42,6 +46,18 @@ const IS_DEPOSIT_ADDRESS: Readonly boolea stellar: (address) => StrKey.isValidEd25519PublicKey(address), sui: (address) => SUI_ADDRESS.test(address), solana: (address) => isAddress(address), + avalanche: (address) => + isEvmAddress(address, { strict: false }) && + address.toLowerCase() !== zeroAddress && + address.toLowerCase() !== AVALANCHE_USDC.toLowerCase(), +} + +/** + * The token contract an order on this chain must name. On Avalanche only Circle's native USDC counts + * as payment; bridged USDC.e sent there is not paid out, so an order for any other contract is refused. + */ +const USDC_CONTRACT: Readonly>> = { + avalanche: AVALANCHE_USDC, } export interface LinqOrderInput { @@ -295,6 +311,14 @@ export function createLinqClient(options: LinqClientOptions = {}): { if (chain !== 'stellar' && input.coin !== 'usdc') { return { ok: false, code: 'rejected', message: 'This payout is ordered in USDC only.' } } + // Linq refuses a C-Chain refund address whose checksum is wrong, so it is sent checksummed. + let refundAddress = input.refundAddress + if (chain === 'avalanche') { + if (!isEvmAddress(refundAddress, { strict: false })) { + return { ok: false, code: 'rejected', message: 'The refund address is not on Avalanche.' } + } + refundAddress = getAddress(refundAddress) + } const res = await call('/b2b/offramp', { method: 'POST', body: { @@ -307,7 +331,7 @@ export function createLinqClient(options: LinqClientOptions = {}): { bankCode: input.bankCode, bankName: input.bankName, accountName: input.accountName, - refundAddress: input.refundAddress, + refundAddress, customerRef: input.customerRef, idempotencyKey: input.idempotencyKey, }, @@ -322,9 +346,14 @@ export function createLinqClient(options: LinqClientOptions = {}): { const amountCoin = num(body['amountStableCoin']) // Off Stellar the order must also be for exactly the USDC asked: that is what the wallet signs. const exactAmount = chain === 'stellar' || amountCoin === input.amountStableCoin + const contract = USDC_CONTRACT[chain] + const coin = str(body['coin']).toLowerCase() const matches = str(body['chain']).toLowerCase() === chain && - str(body['coin']).toLowerCase() === input.coin && + // Where the contract is checked it names the asset, so a missing coin name is no doubt. + (coin === input.coin || (contract !== undefined && coin === '')) && + (contract === undefined || + str(body['coinType']).toLowerCase() === contract.toLowerCase()) && IS_DEPOSIT_ADDRESS[chain](address) && exactAmount && amountCoin > 0 && diff --git a/apps/dapp/lib/support/assistant.ts b/apps/dapp/lib/support/assistant.ts index f6914bc8..daf31af5 100644 --- a/apps/dapp/lib/support/assistant.ts +++ b/apps/dapp/lib/support/assistant.ts @@ -37,7 +37,7 @@ const HELP_FACTS = `About Intent: - Intent is a chat app. People type what they want, for example "swap 10 USDC to XLM", "send 5 USDC to
" or "off-ramp $20 to my bank", AI agents compete to find the best route, and the person signs the transaction in their own wallet. Agents never hold anyone's money. - Chains: Stellar, Solana, Sui, NEAR, Avalanche and Monad. The chain is picked in the switcher and is part of the page address. - An off-ramp pays a bank account in naira (and some other currencies). The person types the amount, picks or confirms the bank account, reviews the card, then presses Sign to send the deposit from their wallet. -- Naira off-ramps on Stellar, Solana and Sui are paid out by Linq. Avalanche and NEAR off-ramps are paid out by Weave. +- Naira off-ramps on Stellar, Solana, Sui and Avalanche are paid out by Linq. NEAR off-ramps, and Avalanche off-ramps Linq can't take, are paid out by Weave. What an order's status means: - waiting: the order is made but no deposit has left the wallet. Nothing has moved. The person can go back to the card and press Sign, or let it expire. diff --git a/apps/dapp/lib/weave/best-payout.ts b/apps/dapp/lib/weave/best-payout.ts index 5467f3ed..871890bc 100644 --- a/apps/dapp/lib/weave/best-payout.ts +++ b/apps/dapp/lib/weave/best-payout.ts @@ -26,7 +26,7 @@ export interface PayoutOffer { * fixed that, but Stellar naira stays on Linq's flow, which people have used. NEAR opened the same day. */ export const PAYS_NAIRA: Readonly> = { - linq: ['stellar', 'sui', 'solana'], + linq: ['stellar', 'sui', 'solana', 'avalanche'], weave: ['solana', 'avalanche', 'sui', 'near'], } diff --git a/apps/dapp/lib/weave/deposit/avalanche.ts b/apps/dapp/lib/weave/deposit/avalanche.ts index afec5df7..569ad776 100644 --- a/apps/dapp/lib/weave/deposit/avalanche.ts +++ b/apps/dapp/lib/weave/deposit/avalanche.ts @@ -27,7 +27,8 @@ import type { DepositChain, DepositExpectation } from '../types' const USDC_DECIMALS = 6 /** Circle's native USDC on the C-Chain, not the bridged USDC.e. */ -const USDC: Address = '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E' +export const AVALANCHE_USDC: Address = '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E' +const USDC = AVALANCHE_USDC const RPC_TIMEOUT_MS = 8_000 const RECEIPT_TIMEOUT_MS = 20_000 const EXPLORER_TX = 'https://snowtrace.io/tx/' diff --git a/apps/dapp/lib/weave/linq-cashout.ts b/apps/dapp/lib/weave/linq-cashout.ts index 16c95cd9..b086fad5 100644 --- a/apps/dapp/lib/weave/linq-cashout.ts +++ b/apps/dapp/lib/weave/linq-cashout.ts @@ -65,13 +65,14 @@ export type LinqPlacement = } /** The chains where a naira cash-out can go to Linq or Weave. Stellar naira has its own Linq form. */ -export function comparesLinq(chain: CashoutChain): chain is 'sui' | 'solana' { - return chain === 'sui' || chain === 'solana' +export function comparesLinq(chain: CashoutChain): chain is 'sui' | 'solana' | 'avalanche' { + return chain === 'sui' || chain === 'solana' || chain === 'avalanche' } /** - * Places every Sui or Solana naira cash-out with Linq, whatever Weave quotes, because Linq locks the - * naira it pays and Weave's estimate comes in lower than shown. Decided by the user, 10 November 2026. + * Places every Sui, Solana or Avalanche naira cash-out with Linq, whatever Weave quotes, because Linq + * locks the naira it pays and Weave's estimate comes in lower than shown. Decided by the user for Sui + * and Solana on 10 November 2026, and for Avalanche on 16 November 2026, once Linq took C-Chain USDC. * * Weave takes it only when Linq can't: a bank it doesn't know, a lookup or order that fails, or an * answer that can't be confirmed. An order Linq made but this app doesn't keep is never shown to