Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/dapp/app/api/cashout/quote/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response> {
Expand All @@ -45,7 +45,7 @@ export async function GET(request: Request): Promise<Response> {

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
Expand Down
71 changes: 71 additions & 0 deletions apps/dapp/lib/__tests__/linq-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> = {}) =>
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(
Expand Down
102 changes: 98 additions & 4 deletions apps/dapp/lib/__tests__/linq-sui-cashout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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()
Expand All @@ -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' })
Expand Down Expand Up @@ -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<string, unknown> = {}) =>
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}&currency=NGN&amount=1`, {
Expand All @@ -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)
})
})

Expand Down
17 changes: 12 additions & 5 deletions apps/dapp/lib/__tests__/weave-best-payout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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')
})
Expand Down
39 changes: 34 additions & 5 deletions apps/dapp/lib/linq/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
*/

Expand All @@ -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}$/
Expand All @@ -42,6 +46,18 @@ const IS_DEPOSIT_ADDRESS: Readonly<Record<LinqChain, (address: string) => 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<Partial<Record<LinqChain, string>>> = {
avalanche: AVALANCHE_USDC,
}

export interface LinqOrderInput {
Expand Down Expand Up @@ -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: {
Expand All @@ -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,
},
Expand All @@ -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 &&
Expand Down
2 changes: 1 addition & 1 deletion apps/dapp/lib/support/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <address>" 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.
Expand Down
2 changes: 1 addition & 1 deletion apps/dapp/lib/weave/best-payout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<PayoutProvider, readonly CashoutChain[]>> = {
linq: ['stellar', 'sui', 'solana'],
linq: ['stellar', 'sui', 'solana', 'avalanche'],
weave: ['solana', 'avalanche', 'sui', 'near'],
}

Expand Down
3 changes: 2 additions & 1 deletion apps/dapp/lib/weave/deposit/avalanche.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/'
Expand Down
Loading
Loading